m1r1k m1r1k - 1 year ago 407
React JSX Question

HOC vs Wrapper in render function

Is there any difference between these two approaches except "code organizing"?

I have bunch of custom input elemts, like TextInput, NumberInput, etc.

I use them directly

const TextInput = (props) => <input type="text" {...props} />

const App = (mainProps) => <div>
<TextInput {...props} errors={['error text']} />

and I have FormInput component that encapsulates error messages rendering for any input component.

const FormInput = (props) => <div>
// Render input here
<span>{props.errors.join(', ')}</span>

I see two different implementation
1) HOC

const FormInputHOC = (C) => {
const FormInput = (props) => <div>
<C {...props} />
<span>{props.errors.join(', ')}</span>

export default FormInputHOC(TextInput)

2) Wrapper

const FormInput = (props) => <div>
<span>{props.errors.join(', ')}</span>

const TextInput = (props) => <FormInput errors={props.errors}>
<input type="text" {...props} />

Answer Source

In your case, there is no real differences, but when you want to do operations on the component state, HOC allows you to code function that can work on this.state. This state will be the one of the component wrapped by the HOC.


With HOC, you can code a componentWillReceiveProps() function that will add or remove some data on the component state each time a component receive props. And you can use this HOC on a several components.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download