skip to Main Content

I am trying to do a list of input where users can provide values for each input. I chose to dynamically render this from an array because the items which values needs to be provided for is coming from a backend server and it’s dynamic (changes per user). Right now, I have been able to render the input according to the array but for some reason the inputs are throwing some inconsistent behaviours like when I type in one input the value isn’t consistent.

Here is code:

const App = () => {
  const [inputs, setInputs] = useState(['name','age','food','gender'])
  const [state, setState] = useState({})
  
  return(
    <div className="">
      {inputs.map((item)=>(
        <input type="text" value={state[item]} placeholder={item} onChange={e =>{
            setState({...state,[item]:e.target.value })
          }} />
      ))}
    </div>
  );
}

I have played around with different data types as array values but no improvement. I also tried to just show one static input and that works, but when I switch back to rendering it dynamically the issue occurs again.

2

Answers


  1. I would advice to add the key prop to your list when rendering. In this instance you can use your item from your inputs, since they are unique

    {inputs.map((item)=>(
        <input key={item} type="text" value={state[item]} placeholder={item} onChange={e =>{
            setState({...state,[item]:e.target.value })
          }} />
      ))}
    

    You can read more about it in this react docs https://react.dev/learn/rendering-lists

    Login or Signup to reply.
  2. May you clarify what inconsistencies you mean ? when the user writes an input each character gets registered until the final input, is that what your asking, if not if your asking that your having inconsistencies to each user ? if you dont mind sharing a screenshot of the issue or a code sandbox like the one below Screenshot

    Code Sandbox

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search