My question is almost the same as this one.
In this case, the person has a map of states created in a hard coded way:
const App = props => {
const [state, changeState] = useState({
name: "",
eventTitle: "",
details: "",
list: "",
toggleIndex: "",
editName: "",
editEventTitle: "",
editDetails: "",
});
The difference is that I want to create those states dynamically, receiving them from another component. I tried something like this but it obviously did not work:
const App = props => {
const [state, changeState] = useState({
props.inputs.map((input, i) =>
input = ""
)
});
Do you know any solution for this?
Assuming props.input is just an array of the keys you want, you can populate the state object by iterating through the array and dynamically assigning the state object key with []
const [state, changeState] = useState({});
useEffect(() => {
props.input.forEach(item => changeState(prevState => ({...prevState, [item]: "" })));
}, [props.input])
You can do this by using the props.inputs directly to the state combine it with reduce to create a new object from the inputs array:
const App = props => {
const [state, changeState] = useState(
props.inputs.reduce((acc, cur, arr) => ({
[cur]: "",
...acc
}), {})
);
return (
<ul>
{Object.entries(state).map(([name, value], index) => (
<li key={`li-${index}`}><strong>{name}</strong>: {`"${value}"`}</li>
))}
</ul>
);
}
<App inputs={['name', 'details', 'list', 'editName']}/>
editName: ""
list: ""
details: ""
name: ""
You can check the working Stackblitz here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With