I am encountering an issue with my React component where the visibility and position can be changed by the user.
Currently, the visibility can be toggled by adding or removing a CSS class, while the position is adjusted through a function that updates the top and left values after a Drag & Drop interaction.
The problem arises when React fails to update the style upon rerendering the component for visibility changes.
class MoveableCard extends React.Component {
...
render() {
...
return <div className={(this.props.isVisible ? '' : 'hide')}
draggable="true" onDragStart={dragStart}
style={{top:'initial', left:'initial'}}>
...
</div>
}
}
function dragStart(event) {
var style = window.getComputedStyle(event.target, null)
event.dataTransfer.setData("text/plain", JSON.stringify({
id:event.target.getAttribute('data-reactid'),
x:(parseInt(style.getPropertyValue("left"),10) - event.clientX),
y:(parseInt(style.getPropertyValue("top"),10) - event.clientY)
}))
}
function dragOver(event) {
event.preventDefault()
return false
}
function drop(event) {
let data = JSON.parse(event.dataTransfer.getData("text/plain"))
let el = document.querySelectorAll("[data-reactid='" + data.id + "']")[0]
el.style.left = (event.clientX + parseInt(data.x, 10)) + 'px'
el.style.top = (event.clientY + parseInt(data.y, 10)) + 'px'
event.preventDefault()
return false
}
document.body.addEventListener('dragover',dragOver,false)
document.body.addEventListener('drop',drop,false)
Initially, the Card's style shows
style="top: initial; left: initial;"
.
After being moved, the style changes to style="top: 162px; left: 320px;"
.
However, when the Card is hidden using the class hide
, the style remains the same style="top: 162px; left: 320px;"
, despite attempts to reset it.
I am looking for a solution to force React to update the style accordingly or explore alternative methods to achieve this functionality.