I am trying to render some array/object values in a Modal with React. The problem is when I trigger the modal, values from all modals are rendered.
I searched and learned that it's because I need to store the value ID in state and then tell react to trigger that specific ID not all. But I don't know how to apply it.
Here's a basic example:
const items = [{id: 1, name: 'John', friends: ['Michael', 'Tom']},{id: 2, name:
'Robert', friends: ['Jim', 'Max']}]
const [show, setShow] = useState(false);
<>
{items.map((i) => {
<div key={i.id}>
<h1>{i.name}</h1>
<button onClick={() => setShow(true)}>View Friends</button>
</div>;
})}
{show ? <div>{items.map((i) => i.friends)}</div> : null} **I know this is wrong**
</>
So I was wondering how can I store the ID to let React know that I want that specific item to render and not all.
CodePudding user response:
Save id
in state
const [show, setShow] = useState(null);
...
<button onClick={() => setShow(i.id)}>View Friends</button>
...
{show !== null && <div>{ items.find(i => i.id === show).friends }</div>}
CodePudding user response:
You have to save the selection id in the component state.
const items = [{id: 1, name: 'John', friends: ['Michael', 'Tom']},{id: 2, name:
'Robert', friends: ['Jim', 'Max']}]
const [show, setShow] = useState(false);
const [id, setId] = useState(null);
<>
{items.map((i) => {
<div key={i.id}>
<h1>{i.name}</h1>
// set the user's selection into another local state
<button onClick={() => { setShow(true); setId(i.id)}}>View Friends</button>
</div>;
})}
// filter the current records for the selected id
{show && <div>{items.filter(obj => obj.id === id)?[0].friends}</div>}
</>
CodePudding user response:
First store the selected record in state like
const [selectedRecord,setSelectedRecord] = useState(null);
now when you click on button update selected record like this
<button onClick={() => { setShow(true); setSelectedRecord(i)}}>View Friends</button>
and use it to render inside modal like this
{show ? <div>name :{selectedRecord.name} Friends :{ selected.friends.join(',')}</div> : null}
Finally your code should be like this
const items = [{id: 1, name: 'John', friends: ['Michael', 'Tom']},{id: 2, name:
'Robert', friends: ['Jim', 'Max']}]
const [show, setShow] = useState(false);
const [selectedRecord,setSelectedRecord] = useState(null);
<>
{
items.map((i) => {
<div key={i.id}>
<h1>{i.name}</h1>
// set the user's selection into another local state
<button onClick={() => { setShow(true); setSelectedRecord(i)}}>View Friends</button>
</div>;
})}
{show ? <div>name :{selectedRecord.name} Friends :{ selected.friends.join(',')}</div> : null}
</>