Wednesday, July 27, 2016

Higher Order Components: A React Application Design Pattern

In this article we will discuss how to use Higher Order Components to keep your React applications tidy, well structured and easy to maintain. We’ll discuss how pure functions keep code clean and how these same principles can be applied to React components.

Pure Functions

A function is considered pure if it adheres to the following properties:

  • All the data it deals with are declared as arguments
  • It does not mutate data it was given or any other data (these are often referred to as side effects).
  • Given the same input, it will always return the same output.

For example, the add function below is pure:

function add(x, y) {
  return x + y;
}

However, the function badAdd below is impure:

var y = 2;
function badAdd(x) {  
  return x + y;
}

This function is not pure because it references data that it hasn’t directly been given. As a result, it’s possible to call this function with the same input and get different output:

var y = 2;
badAdd(3) // 5
y = 3;
badAdd(3) // 6

To read more about pure functions you can read “An introduction to reasonably pure programming” by Mark Brown.

Whilst pure functions are very useful, and make debugging and testing an application much easier, occasionally you will need to create impure functions that have side effects, or modify the behavior of an existing function that you are unable to access directly (a function from a library, for example). To enable this we need to look at higher order functions.

Higher Order Functions

A higher order function is a function that when called, returns another function. Often they also take a function as an argument, but this is not required for a function to be considered higher order.

Let’s say we have our add function from above, and we want to write some code so that when we call it we log the result to the console before returning the result. We’re unable to edit the add function, so instead we can create a new function:

function addAndLog(x, y) {  
  var result = add(x, y);
  console.log('Result', result);
  return result;
}

We decide that logging results of functions is useful, and now we want to do the same with a subtract function. Rather than duplicate the above, we could write a higher order function that can take a function and return a new function that calls the given function and logs the result before then returning it:

function logAndReturn(func) {  
  return function() {  
    var args = Array.prototype.slice.call(arguments);
    var result = func.apply(null, args);
    console.log('Result', result);
    return result;
  }
}

Now we can take this function and use it to add logging to add and subtract:

var addAndLog = logAndReturn(add);
addAndLog(4, 4) // 8 is returned, ‘Result 8’ is logged

var subtractAndLog = logAndReturn(subtract);
subtractAndLog(4, 3) // 1 is returned, ‘Result 1’ is logged;

logAndReturn is a HOF because it takes a function as its argument and returns a new function that we can call. These are really useful for wrapping existing functions that you can’t change in behavior. For more information on this, check M. David Green’s article “Higher-Order Functions in JavaScript which goes into much more detail on the subject.

Additionally you can check out this CodePen, which shows the above code in action.

Higher Order Components

Moving into React land, we can use the same logic as above to take existing React components and give them some extra behaviours.

In this section we're going to use React Router, the de facto routing solution for React. If you'd like to get started with the library I highly recommend the React Router Tutorial on GitHub.

React Router’s Link component

React Router provides a <Link> component that is used to link between pages in a React application. One of the properties that this <Link> component takes is activeClassName. When a <Link> has this property and it is currently active (the user is on a URL that the link points to), the component will be given this class, enabling the developer to style it.

This is a really useful feature, and in our hypothetical application we decide that we always want to use this property. However, after doing so we quickly discover that this is making all our <Link> components very verbose:

<Link to="/" activeClassName="active-link">Home</Link>
<Link to="/about" activeClassName="active-link">About</Link>
<Link to="/contact" activeClassName="active-link">Contact</Link>

Notice that we are having to repeat the class name property every time. Not only does this make our components verbose, it also means that if we decide to change the class name we’ve got to do it in a lot of places.

Continue reading %Higher Order Components: A React Application Design Pattern%


by Jack Franklin via SitePoint

Digging Deeper into WordPress Hooks and Filters

WordPress comes loaded with a series of hooks and filters that let you hook into specific parts of when WordPress operates. For example, you can attach a custom function so that it executes when the WordPress save_post action is called, giving you access to the post being saved. Plugins and themes are an area where […]

Continue reading %Digging Deeper into WordPress Hooks and Filters%


by Simon Codrington via SitePoint

Julien Dargelos

I’m a french web developer and I love it. My Website show who I am and what I do.


by csreladm via CSSREEL | CSS Website Awards | World best websites | website design awards | CSS Gallery

Mix The Play

It’s your turn to be the director: direct your own version of A Midsummer Night’s Dream. Every decision you make will change the scene entirely.


by csreladm via CSSREEL | CSS Website Awards | World best websites | website design awards | CSS Gallery

This Week's HTML5 and Browser Technology News (Issue 250)


Read this e-mail on the Web

FrontEnd Focus

formerly HTML5 Weekly

Chris Coyier
You’re in a container element with a limited width but want to run a full-width image or other ‘breakout’. What are the options? Some clever tricks here.


Jeremy Thomas
A click-by-click journey, starting with a basic page, and progressing to consider content, spacing, color and contrast. This has been very popular online this week.


Google Developers
A look at how a service worker can help you capture offline analytics to send to Google Analytics later on.


Progress  Sponsored
If you're a HTML5/JS dev, maybe you have already jumped in on a responsive project and would like to learn more. If not, responsive web design will probably be a requirement in the near future. This whitepaper will give you the must-know responsive web.

Progress

Michael Ngo
An in-depth walkthrough, complete with code and examples, of pushing SVG for building advanced Web-based animations.


Jake Archibald
This mechanism prevents pages on other origins from accessing your page’s window object via window.opener.


Brad Frost
A code review of some form elements led to deep thoughts on how to approach crafting frontend code overall, plus a neat 20 minute HTML code review by Jonathan Snook.


Paul Kinlan
Paul Lewis explains the new CSS Containment property (contain) which lets developers limit the scope of the browser’s styles, layout and paint work.


Jobs

In brief

Curated by Peter Cooper and published by Cooper Press.

Unsubscribe : Change email address : Read this issue on the Web

Published by Cooper Press Ltd. Fairfield Enterprise Centre, Louth, LN11 0LS, UK


by via HTML5 Weekly

Prisma: The Rise and Fall and Rise of the One-Trick-Pony Filter

Hassle-Free Filesystem Operations during Testing? Yes Please!

When working with the filesystem in our tests suites, a big concern is cleaning up the temporary files after each test runs. However, if for any reason the test's execution is interrupted before the cleanup phase, further tests might fail, as the environment has not been cleaned up.

In this post, we will use a library named vfsStream to create filesystem mocks. It's little more than a wrapper around a virtual filesystem, which also works very nicely with PHPUnit.

Note This post requires a basic understanding of unit testing and PHPUnit.

To have something to test, we'll write a simple class for creating files:

<?php
// FileCreator.php
class FileCreator {

    public static function create($path, $name, $content)
    {
        $file_name = rtrim($path, '/') . '/' . $name;

        if (file_put_contents($filename, $content)){
            return true;
        }
        return false;
    }
}

Inside the class, we have a create() method, which accepts the filename, content, and a path to which to save it.

To test the class, we first take the traditional approach, and create a test class without using a virtual filesystem. Then, we'll bring vfsStream into the game to see how it can simplify the testing process for us.

Traditional Approach

<?php

class FileCreatorTest {

    protected $path;

    public function setUp()
    {
        $this->path = sys_get_temp_dir();
    }

    public function tearDown()
    {
        if (file_exists($this->path . '/test.txt')) {
            unlink($this->path . '/test.txt');
        }
    }

    public function testCreate()
    {
        $this->assertTrue(FileCreator::create($this->path, 'test.txt', 'Lorem ipsum dolor sit amet'));
        $this->assertFileExists($this->path . '/test.txt');

    }

In the above, we define the temporary directory (in setUp()) which we'll use for our temporary files by using PHP's sys_get_temp_dir(). The function returns the system's directory path for temporary files.

Continue reading %Hassle-Free Filesystem Operations during Testing? Yes Please!%


by Reza Lavaryan via SitePoint