When I set the opacity of element in someFunc, it doesn't set last element's opacity but one before. Ref is not updated instantly.
Elements' opacity will stay "1" in normal. This opacity change is needed just for the last added element and for short time.
How can I access the last element of that div in the same line of someFunc ?
const MyComponent = () => {
const [divisions, setDivisions] = useState([]);
const itemRef = useRef();
const someFunc = () => {
const newDivision = {
id: "someId",
someData: "someText"
}
setDivisions(prevState => [...prevState, newDivision])
itemRef.current.style.opacity = "0.7"
}
return (
<>
<div onClick={someFunc}>Button</div>
<div className="container">
{divisions.map((item, key) => {
return <div id={item.id} ref={itemRef}>item.someData</div>
})
}
</div>
</>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
CodePudding user response:
You can easily add the ref
to the last item by counting divisions
(minus one as you're matching to the key which starts at zero - I added brackets ( ... ) for clarity but they're optional):
ref={key === (divisions.length - 1) && itemRef}
CodePudding user response:
That is because you are using the same ref on the mapped elements. simply change your div to the below
<div id={item.id} ref={(el) => (itemRef.current[key] = el)}>item.someData</div>
and your function to this
const someFunc = () => {
const newDivision = {
id: "someId",
someData: "someText"
}
setDivisions(prevState => [...prevState, newDivision])
for (let i = 0; i < itemRef.current.length; i ) {
if(i === (itemRef.current.length - 1))
{
itemRef.current[i].style.opacity = "0.7"
}
}
}
then inform react by calling useEffect
useEffect((console.log(itemRef)) => {},[itemRef])