so I'm facing an issue where I am not able to change the width of DOM node using useRef. Im using the onDragEnd event to trigger the change of the width on the selected node only. I'm setting the width by changing the 'elementRef.current.style.width property. But the change is not being reflected on the frontend.
Heres my code:
import React, { useEffect, useState, useRef } from "react";
import timelineItems from "../timelineItems";
import "../index.css";
const TimeLine = () => {
const [sortedTimeline, setTimelineSorted] = useState([]);
const increaseDateDomRef = useRef(null);
let usedIndex = [];
useEffect(() => {
let sortedResult = timelineItems.sort((a, b) => {
return (
new Date(a.start) -
new Date(b.start) +
(new Date(a.end) - new Date(b.end))
);
});
setTimelineSorted(sortedResult);
}, []);
const increaseEndDate = (e) => {
};
const increaseEndDateFinish = (e, idx) => {
//Im setting the width here but it is not being reflected on the page
increaseDateDomRef.current.style.width = '200px';
console.log(increaseDateDomRef.current.clientWidth);
};
return (
<div className="main">
{sortedTimeline.map((item, idx) => {
return (
<div key={idx}>
<p>{item.name}</p>
<p>
{item.start} - {item.end}
</p>
<div className="wrapper">
<div className="circle"></div>
<div
className="lineDiv"
ref={increaseDateDomRef}
draggable
onDragStart={(e) => increaseEndDate(e)}
onDragEnd={(e) => increaseEndDateFinish(e, idx)}
>
<hr className="line" />
</div>
<div className="circle"></div>
</div>
</div>
);
})}
</div>
);
};
export default TimeLine;
first of all this may not be working because you are using a single reference for multiple elements.
This answer on another post may help you https://stackoverflow.com/a/65350394
But what I would do in your case, is something pretty simple.
const increaseEndDateFinish = (e, idx) => {
const target = e.target;
target.style.width = '200px';
console.log(target.clientWidth);
};
You don't have to use a reference since you already have the reference on the event target.