We have an object 'Schema' with inputs for a form. We map through the inputs and return a custom component for each that then does the rest of the work. The problem is that:
1) Custom components can't have a key attribute, as key is a special property used by React and is not passed to the children.
2) The first item in a list must have a key attribute so that React can know how to update the components.
If your first item in the list is a custom Component, then these two are mutually exclusive. We can get around this problem by surrounding the QuestionBlock with a div or any other generic element and adding a key attribute to it. However this results in code and HTML that looks sloppy, having excessive divs just to work around this problem. Is there any other cleaner way to do it. Below is the code we had before:
render() {
return (
<div className="App">
{Object.keys(Schema.inputs).map((key,index) => {
let data = Object.assign({}, Schema.inputs[key]);
data.index = index;
return <QuestionBlock key={index} {...data} />;
}}
</div>
);
}
Warning shown in console when using the above code:
Warning: QuestionBlock:
keyis not a prop. Trying to access it will result inundefinedbeing returned. If you need to access the same value within the child component, you should pass it as a different prop.
And below here is the code that works, but looks messy:
render() {
return (
<div className="App">
{Object.keys(Schema.inputs).map((key,index) => {
let data = Object.assign({}, Schema.inputs[key]);
data.index = index;
return <div key={index}>
<QuestionBlock {...data} />
</div>;
}}
</div>
);
}
Many thanks in advance!