skip to Main Content

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


  1. If you are wanting to create variables dynamically like var0, var1, var2, then just use an array.

    const userInputs = [];
    const setUserInputs = [];
    userInputs.forEach((element, index) => {
      const [xuserInput, setUserInput] = useState('');
      userInputs.push(xuserInput);
      setUserInputs.push(setUserInput);
    });
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. 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:

     const userInputs = ['hoge', '123', 'aaa'];
      const [inputs, setInputs] = useState({});
    
      userInputs.forEach((element, index) => {
        const stateName = 'userInput' + index;
        if (!inputs.hasOwnProperty(stateName)) {
          setInputs((prevInputs) => ({ ...prevInputs, [stateName]: '' }));
        }
      });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search