m1r1k m1r1k - 1 month ago 6
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']} />
</div>


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>
</div>


I see two different implementation
1) HOC

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

export default FormInputHOC(TextInput)


2) Wrapper

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

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

Answer

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.

Example:

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.