reactjsreact-hooksreact-hoc

How to wrap a function which contains hooks with HoC


As the title suggest I want to be able to wrap a function (which contains) hooks in a HoC.

In the example below I want to be able to wrap the JSX from TestView with div element tag where the className="someClassName". However I get the following exception:

Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See for tips about how to debug and fix this

import React, { Component } from 'react'

function wrap(component) {
    let calledComponent = component()
    return (
        <div className="someClassName">
          {calledComponent}
        </div>
    );
  }


function TestView() {
    const [ val, setValue] = React.useState('Initial Value');
    return (
        <div>
            <input type="text" value={val} onChange={event=>setValue(event.target.value)}/>
        </div>
    )

 }

 export default wrap(TestView);

Solution

  • Concretely, a higher-order component is a function that takes a component and returns a new component. react docs

    so, you have to have a function that returns a component, maybe like this.

    import React, { useState } from 'react';
    import '../styles.css';
    
    const withStyle = WrappedComponent => {
      return function WithStyle() {
        return (
          <div className='myClassStyle'>
            <WrappedComponent />
          </div>
        );
      };
    };
    
    function TestView() {
      const [val, setVal] = useState('Initial Value');
      return (
        <div>
          <input type='text' value={val} onChange={e => setVal(e.target.value)} />
        </div>
      );
    }
    
    export default withStyle(TestView);