My idea is when the mouse enters the item, extract item, it will update the element and change its text here is the code :
{skillItems.map((item, index) => {
const { id, name} = item;
return (
<li
key={id}
className="singleChart"
onMouseOver={() => setOver(true)}
onm ouseLeave={() => setOver(false)}
>{overEffect ? name : ""}</li>)
But when the mouse over the item, all the other items also change. what should I do?
Thank you
CodePudding user response:
Also save the index of the item on mouseOver and then check saved index with the current mouseOver item.
CodePudding user response:
you need to save the id of the item too for the item of mouse over
skillItems.map((item, index) => {
const { id, name} = item;
return (
<li
key={id}
className="singleChart"
onMouseOver={() => setOver({value:true,id})}
onm ouseLeave={() => setOver({value:false,id})}
>
{(overEffect.value&&overEffect.id) ? name : ""}</li>)
CodePudding user response:
If you need to change only one item then you can have only one state which will show the index of item in which moues will be overed. So you can do this
{skillItems.map((item, index) => {
const { id, name} = item;
return (
<li
key={id}
className="singleChart"
onMouseOver={() => setOver(index)}
onm ouseLeave={() => setOver(-1)}
>{overEffect === index ? name : ""}</li>)
or the same thing whith ids
{skillItems.map((item, index) => {
const { id, name} = item;
return (
<li
key={id}
className="singleChart"
onMouseOver={() => setOver(id)}
onm ouseLeave={() => setOver(null)}
>{overEffect === id ? name : ""}</li>)
CodePudding user response:
In this case you need a bit more complex state object. I used an object to keep state for each item in the list. One way of doing is like this: https://codesandbox.io/s/https-stackoverflow-com-questions-69612695-update-the-specific-item-in-map-loop-69613214-69613214-z5o17?file=/src/App.js - let me know if this is accessible to you.
What is done here is that we had to construct state object using reduce method and later we have to take care how we set new state (not to override something).
import React from "react";
function App() {
const skillItems = [
{
id: 1,
name: "111"
},
{
id: 2,
name: "222"
},
{
id: 3,
name: "333"
}
];
const stateObj = skillItems.reduce((acc, curr) => {
const keys = Object.keys(curr);
if (!acc) {
return Object.assign({}, { [keys[0] curr.id]: true });
}
return Object.assign(acc, { [keys[0] curr.id]: true });
}, null);
const [overEffect, setOver] = React.useState(stateObj);
console.log("overEffect", overEffect);
return (
<div className="App" style={{ backgroundColor: "pink" }}>
{skillItems.map((item, index) => {
const { id, name } = item;
const key = "id" id;
return (
<li
key={id}
onMouseOver={() => setOver({ ...overEffect, [key]: false })}
onm ouseLeave={() => setOver({ ...overEffect, [key]: true })}
>
{overEffect[key] ? name : ""}
</li>
);
})}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<App />
</StrictMode>,
rootElement
);