Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass an HTML element to a higher-order function (HOC) in React?

I often use HOCs to provide additional functionality to an existing React component, which is pretty straightforward:

import Component from '/path/to/Component';
import higherOrderComponent from '/path/to/higherOrderComponent';

const EnhancedComponent = higherOrderComponent(Component);

However, I need to wrap a simple HTML input, which doesn't exist as a standalone React component. I tried

const EnhancedInput = higherOrderComponent(<input />);

and got the following error:

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

How can I properly pass the input?

like image 640
ericgio Avatar asked Feb 18 '18 01:02

ericgio


2 Answers

Pass the string name of the HTML element you want to wrap:

const EnhancedInput = higherOrderComponent('input');

The error clued me into what I needed to do and made more sense when breaking down what JSX is doing. <input /> is simply JSX syntactic sugar for React.createElement('input').

If the HOC looks something like this:

const higherOrderComponent = (Component) => {
  return class extends React.Component {
    render() {
      return (
        <Component {...} />
      );
    }
  }
};

then the render method is ultimately returning

React.createElement(Component, {...});

Therefore, passing the string 'input' to the HOC means it will return React.createElement('input', {...});, which is the same as <input /> as asserted above.

like image 190
ericgio Avatar answered Nov 10 '22 16:11

ericgio


Another solution is to use a function that returns the HTML you want.

const EnhancedComponent = higherOrderComponent(()=><input />)

like image 33
fabioDMFerreira Avatar answered Nov 10 '22 16:11

fabioDMFerreira