Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding React Higher-Order Components

Can someone please explain Higher-order components in React. I have read and re-read the documentation but cannot seem to get a better understanding. According to the documentation, HOCs help remove duplication by creating a primary function that returns a react component, by passing arguments to that function. I have a few questions on that.

  • If HOCs create a new enhanced component, can it be possible not to pass in any component as argument at all?
  • In an example such as this, which is the higher order component, the Button or the EnhancedButton.
  • I tried creating one HOC like this:

    // createSetup.js
    import React from 'react';
    
    export default function createSetup(options) {
        return class extends React.Component {
            constructor(props) {
                super(props);
    
                this.state = {};
    
                this.testFunction = this.testFunction.bind(this);
            }
    
            testFunction() {
                console.log("This is a test function");
            }
    
            render() {
                return <p>{options.name}</p>
            }
        }
    }
    
    
    // main.js
    import React from 'react';
    import {render} from 'react-dom';
    import createSetup from './createSetup';
    
    render((<div>{() => createSetup({name: 'name'})}</div>),
            document.getElementById('root'););
    

Running this does not show the HOC, only the div

Can anyone help out with a better example than the ones given?

like image 445
cr05s19xx Avatar asked Aug 29 '17 09:08

cr05s19xx


People also ask

What is higher-order component in React with example?

Higher-Order Components are not part of the React API. They are the pattern that emerges from React's compositional nature. The component transforms props into UI, and a higher-order component converts a component into another component. The examples of HOCs are Redux's connect and Relay's createContainer.

Do people still use higher-order components?

In a modern React world, everyone uses function components with React Hooks. However, the concept of higher-order components (HOC) is still applicable in a modern React world, because they can be used for class components and function components.

What is higher-order component in React functional component?

A higher-order component is a function that takes a component and returns a new component. React's Higher Order Component is a pattern that stems from React's nature that privileges composition over inheritance.

What is HOC and Hof?

React's Higher Order ComponentsHigher-Order Components (HOC) stem from the concept of Higher-Order Functions (HOF) which is called this way whenever it takes a function as argument or returns a function with its return statement.


3 Answers

A HOC is a function that takes a Component as one of its parameters and enhances that component in some way.

If HOCs create a new enhanced component, can it be possible not to pass in any component as argument at all?

Nope, then it wouldn't be a HOC, because one of the conditions is that they take a component as one of the arguments and they return a new Component that has some added functionality.

In an example such as this, which is the higher order component, the Button or the EnhancedButton.

EnhanceButton is the HOC and FinalButton is the enhanced component.

I tried creating one HOC like this: ... Running this does not show the HOC, only the div

That's because your createSetup function is not a HOC... It's a function that returns a component, yes, but it does not take a component as an argument in order to enhance it.

Let's see an example of a basic HOC:

const renderWhen = (condition, Component) =>
  props => condition(props)
    ? <Component {...props} />
    : null
);

And you could use it like this:

const EnhancedLink = renderWhen(({invisible}) => !invisible, 'a');

Now your EnhancedLink will be like a a component but if you pass the property invisible set to true it won't render... So we have enhanced the default behaviour of the a component and you could do that with any other component.

In many cases HOC functions are curried and the Component arg goes last... Like this:

const renderWhen = condition => Component =>
  props => condition(props)
    ? <Component {...props} />
    : null
);

Like the connect function of react-redux... That makes composition easier. Have a look at recompose.

like image 188
Josep Avatar answered Sep 27 '22 20:09

Josep


In short, If you assume functions are analogues to Components, Closure is analogous to HOC.

like image 45
Henok Tesfaye Avatar answered Sep 27 '22 19:09

Henok Tesfaye


Try your createSetup.js with:

const createSetup = options => <p>{options.name}</p>;

and your main.js

const comp = createSetup({ name: 'name' });
render((<div>{comp}</div>),
  document.getElementById('root'));
like image 34
Curro González Avatar answered Sep 27 '22 18:09

Curro González