I’d like to declare the same number of useState hooks with the userInputs array’s length.
And I want to name them like userInput0, userInput1, userInput2,,,userInputN
But "const [userInput+index.toString(), setUserInput] = useState(”)" throws an error.
How can I fix it?
'use client';
import { useState } from 'react';
userInputs = ['hoge', '123', 'aaa'];
userInputs.array.forEach((element, index) => {
const [userInput+index.toString(), setUserInput] = useState('')
});
3
Answers
If you are wanting to create variables dynamically like
var0
,var1
,var2
, then just use an array.I think despite that this is something that you could probably do I wouldn’t recommend it because it could lead to unexpected behavior
There are some rules in order to use hooks and you are breaking one of them
Don’t call Hooks inside loops, conditions, or nested functions
https://legacy.reactjs.org/docs/hooks-rules.html
I recommend you that you create component with its own state and with your array render 3 different components with their states
To dynamically declare multiple useState hooks with names like "userInput0", "userInput1", "userInput2", etc., you can’t directly concatenate the variable name as a string. However, you can achieve this using an object or an array to store the state values. Here’s an example of how you can accomplish it: