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?
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.
Another solution is to use a function that returns the HTML you want.
const EnhancedComponent = higherOrderComponent(()=><input />)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With