score:6

Accepted answer

Issue

You are using a single boolean edit state value to trigger the edit mode of all mapped elements.

Solution

Use some edit state that you can correlate to your data, like the index or an item id property. Since I don't see any GUIDs used I'll demo with index.

  1. Use the element index to identify what is in "edit" mode, null means nothing has the "edit" mode.

     const [editIndex, setEditIndex]= useState(null);
    
  2. Update the toggle button to toggle a new index or back to null if the same button is clicked

     <Button
       size="small"
       onClick={() => setEditIndex(editIndex => editIndex === index ? null : index)}
     >
       Edit
     </Button>
    
  3. Match the saved editIndex state to the currently mapped element to conditionally render the messaging.

     {editIndex === index && <h1>Want to see this in only one card</h1>}
    

Additional Note

I see you have a delete button:

<Button size="small" onClick={()=> deleted(oneitem._id)} >Delete</Button>

If you are deleting elements from the underlying data then you will want to not use the array index as the React key. Instead you should use a uniquely identifying property, like _id, of each element (they need only be unique among siblings). So instead of using the index to set the "edit" mode you would use _id instead.

score:1

This problem comes up for you because you're using a common edit value throughout the map. So, if you change the main value of "edit" to "true" (as in this case), it will consider the edit as true for all the cards.

No, Here's what you can try doing ( I'm considering you can edit only one card at a time ) instead of keeping the edit as a boolean value (true|false) use it as an integer value to store the index of the card in your array.

Steps :

  1. By default keep edit = null
  2. the setEdit function can become something like this: (considering class based state)

setEdit(editVal) => {
  if(this.state.edit === editVal){
    this.setState({
      edit: null
      })
  }
  else{
    this.setState({
      edit: editVal
    }
  }
}

  1. and while calling the setEdit method call it like this:

onClick={()=> setEdit(index)}

  1. Now everytime you click the edit button the edit value either changes to a new index value or to a null.

  2. One last change is to replace this:

{edit && <h1>Want to see this in only one card</h1>}

with this

{edit===index && <h1>Want to see this in only one card</h1>}

Concluding:

We first moved the edit value to Integer or null, Then on clicking edit the index value of the element in the array is assigned to "edit". once this happens, we're checking if the edit value is equals to the index value (step 5), if so, it shows the message only for that card. Once you click edit again, the value of "edit" becomes null (if clicked for the same card).


Related Query

More Query from same tag