1

hello im building a app in react, I have mapped some data from a api and was wondering how add data from a input on to the specific element? im not sure how to accomplish this i have tried a couple different ways, ive tried added the mapped elements id into the state and checking if the the id matched the elements id but i have not been able to make it work, i can get it to apply the tag to every element but i want it to just add to the specific element where you entered the tag.

const [students, setStudents] = useState([]);
  const[tag, setTag] = useState([])

 function createCard(students, n ){
    return(
      <Card 
        key = {n}
        id= {n}
        firstName = {students.firstName}
        lastName = {students.lastName}
        pic = {students.pic}
        email= {students.email}
        company = {students.company}
        skill = {students.skill}
        grades = {students.grades}
        tag={tag}
        newTag={newTag}

    />
    )}


  function newTag(event){
    const createdTag = event.target.value;
    setTag(createdTag)
    console.log(createdTag)
  }
Kevin.
  • 78
  • 1
  • 9

2 Answers2

1

if you want to map over an array in react you can use this approach

  const [students, setStudents] = useState([]);

  {students && students.map ( (student , idx) => 
       <Card
           key = {idx}
           onClick = { (e)=>{
               // add on specefic idx
               let auxiliaryArray = students
               auxiliaryArray = auxiliaryArray.filter( (ele , idx) => {
                  // add logic here
               })
               setStudents(auxiliaryArray)
           }}
        >
)}
zain ul din
  • 1
  • 1
  • 2
  • 23
  • i have already mapped the data. {filter.length ===0 &&
    {students.map(createCard)}
    } . the card has a text input, i want the text from the input added to the specific element.
    – Kevin. Mar 15 '22 at 18:08
  • 1
    check new answer – zain ul din Mar 15 '22 at 18:10
  • 1
    https://stackoverflow.com/questions/586182/how-to-insert-an-item-into-an-array-at-a-specific-index-javascript – zain ul din Mar 15 '22 at 18:12
  • thanks i appreciate it! ill give it a go. – Kevin. Mar 15 '22 at 18:13
  • Hey sorry to bother you again lol but two questions, what kind of logic do you speak of in the auxArray.filter function? everything i have tried is throwing error. and where do i add the props to be passed to the Card doing it this way? – Kevin. Mar 16 '22 at 17:19
0

Array.map always return new array so, don't forget to return all elements

// USAGE
{arr && arr.map ( (ele,idx) => <Com key = {idx} /> ) }