0

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!

1 Answer 1

1

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} />
         )}
Sign up to request clarification or add additional context in comments.

1 Comment

any chance i can get a little mock code example of what you mean?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.