reactjscomponentshigh-order-component

Enhance react component with HOC


I need to create a reusable Camera component, to do that I want to pass a custom record button and I need to attach to it extra functions or overwrite button text.

Here an example:

https://codesandbox.io/s/react-hoc-ksjbf

I have created a hoc.js that takes custom component and try to overwrite text prop but I have this error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

I don't understand was wrong with it, any ideas?


Solution

  • Issue

    You are passing a JSX literal (i.e. object) as a prop value to (be passed to) the higher order component versus a React component.

    recordbutton={<Button text="Original Text" />}
    

    Solution

    Pass a React component instead

    <Camera recordbutton={(props) => <Button text="Original Text" {...props} />} />
    

    or define and pass

    const RecordButton = (props) => <Button text="Original Text" {...props} />;
    
    export default function App() {
      return (
        <div className="App">
          <Camera recordbutton={RecordButton} />
        </div>
      );
    }
    

    or pass the Button component directly

    export default function App() {
      return (
        <div className="App">
          <Camera recordbutton={Button} />
        </div>
      );
    }
    

    So long as you are passing all props on through to the component then the HOC can inject/override prop values.

    Update the HOC to spread the passed props in before providing the overrides, this is so the HOC can actually override them.

    function alterText(Component) {
      return function (props) {
        return <Component {...props} text="new text"  />;
      };
    }