I am trying to parse Object to render HTML element . I am not able to show any HTML element. I think there is some return
statement problem in my code
here is my code https://codesandbox.io/s/objective-sun-i3vy4i?file=/src/App.js
export default function App() {
const [state, setState] = useState({});
const handleChange = (e) => {
setState({
[e.event.name]: e.target.value
});
};
const expractCompont = (component) => {
switch (component.type) {
case "textfield":
return (
<>
<label>{component.label}</label>
<input type="text" name={component.id} onchange={handleChange} />
</>
);
case "number":
return (
<>
<label>{component.label}</label>
<input type="number" name={component.id} onchange={handleChange} />
</>
);
case "select":
return (
<>
<label>{component.label}</label>
<select name={component.id} id={component.id}>
{component.values.map((item, index) => (
<option value={item.value} key={index}>
{item.label}
</option>
))}
</select>
<input
type="number"
name={component.field_107we45}
onchange={handleChange}
/>
</>
);
default:
return <></>;
}
};
const renderComponents = (components) => {
for (let index = 0; index < components.length; index ) {
const element = components[index];
expractCompont(element);
}
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{renderComponents(data.components)}
</div>
);
}
Expected output : Expected output to see input fields ,select box
CodePudding user response:
Your renderComponents
function returns nothing. You need to return an array from it.
const renderComponents = (components) => {
const elementsToRender = [];
for (let index = 0; index < components.length; index ) {
const element = components[index];
elementsToRender.push(expractCompont(element))
}
return elementsToRender;
};
Actually, the renderComponents
function is not really needed, you can put everything at once in return
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{data.components.map(expractCompont)}
</div>
);
CodePudding user response:
You can just update your renderComponents
to this and it will work fine
const renderComponents = (components) => {
return components.map(expractCompont)
};