Jason Tree Jason Tree - 1 year ago 68
Javascript Question

How would you create Higher Order Components (HOCs) in React?

How would you create Higher Order Components (HOCs) in React?

Answer Source

The Answer from https://www.sitepoint.com/react-higher-order-components/ 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 component that is used to link between pages in a React application. One of the properties that this component takes is activeClassName. When a 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 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.

Instead, we can write a component that wraps the component:

var AppLink = React.createClass({  
  render: function() {  
    return (
      <Link to={this.props.to} activeClassName="active-link">

And now we can use this component, which tidies up our links:

<AppLink to="/">Home</AppLink>
<AppLink to="/about">About</AppLink>
<AppLink to="/contact">Contact</AppLink>

You can see this example working on Plunker.

In the React ecosystem these components are known as higher order components because they take an existing component and manipulate it slightly without changing the existing component. You can also think of these as wrapper components, but you’ll find them commonly referred to as higher order components in React-based content.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download