Ben Shekhtman
Ben Shekhtman

Reputation: 615

React setting specific input forms when mapping through array

so I have fetched a bunch of students data from an api and mapped through it, displayed the student info in divs as per common react practices. I want to add a text input field to be able to add tags/comments to every instance of student. Code looks something like this

              <form onSubmit={(e) => handleSubmit(e, i)}>
                <input
                  type='text'
                  placeholder='Add a tag'
                  className='tag__input'
                  value={tag}
                  onChange={(e) => setTag(e.target.value)}
                />
              </form>

const [tag, setTag] is just a useState holding the string value of the comment I want to add. this is expectedly not working as I need because the value of all my input fields is changing, whereas I need only the one specific one to change based on which student I need to leave a comment for. What would be the next steps into setting this logic up? thanks!

Upvotes: 0

Views: 1772

Answers (1)

Aleksandr Smyshliaev
Aleksandr Smyshliaev

Reputation: 420

You should create separate component for student info and input, and put inside of that component useState.

Now you have 1 state for all fields.

UPD, something like

        function StudentEntry({ data, onSubmit }) {
          // one state per entry
          const [tag, setTag] = React.useState('')
 
          return (<>
            <StudentInfo {...data} />

            <form onSubmit={(e) => onSubmit(e, data.id)}>
            <input
              type='text'
              placeholder='Add a tag'
              className='tag__input'
              value={tag}
              onChange={(e) => setTag(e.target.value)}
            />
            </form>
         </>
         }

         // and use somewhere
         {studentsData.map(data => 
            <StudentEntry data={data} key={data.id} onSubmit={handleSubmit} />
         )}

Upvotes: 1

Related Questions