In my code base, I have a higher order component (HOC) that I use to add all the input validation functions to this component. It works great when used on a specific component, such as ...
let NameInput = React.createClass({
render() {
return (
<div>
<label htmlFor="name-input">Name</label>
<input name="name-input" />
</div>
);
}
});
let NameInput = addInputValidation(NameInput);
module.exports = NameInput;
But now I need to define a series of inputs based on an array from the server. Something like that...
let TestApp = React.createClass({
render() {
let names = ['First name', 'Middle name', 'Last name'];
let nameComponents = names.map((name, index) => {
let componentToRender = (
<div key={index}>
<label htmlFor={name}>{name}</label>
<input name={name} />
</div>
);
componentToRender = addInputValidation(componentToRender);
return componentToRender;
})
return (
<div>
<p>Enter some names:</p>
{nameComponents}
</div>
);
}
})
let addInputValidation = function(Component) {
let hoc = React.createClass({
getInitialState() {
return {
isValid: false
};
},
render() {
return (
<div>
<Component {...this.props} />
{this.state.isValid ? null : <p style={{color: "red"}}>Error!!!!</p>}
</div>
);
}
});
return hoc;
}
module.exports = TestApp;
I donβt like the reaction when you try to display the result of the HOC call from another component.
I guess this has something to do with mine componentToRenderbeing not really a React component or something.
So my questions are ...
Why can't I call HOC from another component?
Is there a way to call HOC for each element of the array?
jsfiddle, : https://jsfiddle.net/zt50r0wu/
, :
, , , . (, , ..).
addInputValidation HOC , . , Redux, . , . , HOC React.
, ...
let Select = require('components/presentational-form/select');
let Text = require('components/presentational-form/select');
let CheckboxGroup = require('components/presentational-form/select');
let TestApp = React.createClass({
render() {
let inputs = [{...}, {...}, {...}];
let inputComponents = inputs.map((input, index) => {
let componentToRender = '';
if (input.type === 'select') {
componentToRender = <Select labelText={input.label} options={input.options} />;
} else if (input.type === 'text') {
componentToRender = <Text labelText={input.label} />;
} else if (input.type === 'checkbox') {
componentToRender = <CheckboxGroup labelText={input.label} options={input.options} />;
}
componentToRender = addInputValidation(componentToRender, input.validationIndexes);
return componentToRender;
})
return (
<div>
<p>Enter some names:</p>
{inputComponents}
</div>
);
}
})