I have stored array of objects in a state and I am using map over state to display content. whenever I click on button I get next element not the current. I don’t know why whats happening here. If someone knows please tell me the solution,
Here is my code
function App() {
const [data, setData] = useState([
{
content:
"Lorem ipsum dolor sit amet consectetur adipisicing elit. Molestiae, soluta.",
},
{
content:
"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Soluta aut, commodi laboriosam, eum neque laborum itaque quidem, vel nihil sint debitis est! Aut atque itaque tempora reprehenderit illo nemo consequatur.",
},
]);
const main = useRef(null);
function getMain() {
console.log(main.current);
}
return (
<>
{data.map((t, i) => {
return (
<div key={i} className="main" ref={main}>
<p>{t.content}</p>
<button onClick={getMain}>mainElem</button>
</div>
);
})}
</>
);
}
2
Answers
Sorry, You are wrong, it’s always console.log the last item in the array.
Because when the loop run the last time, it set the ref to the last item
The first mistake is use a ref on to an array of items, you need to have n refs for n items
The solution: