React/mobx: How To Pass Single Item From A Mapped Array Into Another Component And Retrieve Only The Item Associated With The Value Clicked
I have a API which is pushed into a store called PositionStore; as shown const PositionStore = observable({ loading: false, error: '', items: [] as PositionInfo[], LoadPosition()
Solution 1:
If I understand you correctly then you can just store selected item (or its id) inside store, like that:
conststore=observable({loading:false,error:"",selectedItemId:null,selectedItem:null,items: []
});
When mapping over items use onClick
handler to set this value:
onClick={() => {
store.selectedItem = item;
// Or if you prefer store it by id
store.selectedItemId = item.id;
}}
(Better make action for it in real code, I'm inlining it for this example)
Then check that it exists and show it:
<div>
{store.selectedItem && (
<div>
Selected item info:
<h4>{store.selectedItem.name}</h4>
<div>{store.selectedItem.description}</div>
</div>
)}
</div>
If you store it by id then find it (or make computed) before showing:
const selectedItem = store.items.find(
(item) => item.id === store.selectedItemId
);
I've made an example for you on Codesandbox: https://codesandbox.io/s/httpsstackoverflowcomquestions66475608-jh73w?file=/src/App.js
Post a Comment for "React/mobx: How To Pass Single Item From A Mapped Array Into Another Component And Retrieve Only The Item Associated With The Value Clicked"