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 theEnhancedButton
. 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?