Reputation: 97
I found on the internet this code:
class ResizablePanels extends React.Component {
constructor() {
super();
this.state = {
isDragging: false,
panels: [300, 300]
};
}
componentDidMount() {
ReactDOM.findDOMNode(this).addEventListener("mousemove", this.resizePanel);
ReactDOM.findDOMNode(this).addEventListener("mouseup", this.stopResize);
ReactDOM.findDOMNode(this).addEventListener("mouseleave", this.stopResize);
} ....
Full code: https://codesandbox.io/s/elated-ritchie-83rsy?file=/src/index.js
And I´d like to know, how this code snippet above transform to function component, especially how to transform section with componentDidMount(). I know, that I need to use hook "useEffect", but is it possible to use addEventListener for example with "useRef"? I don´t want to use ReactDOM.findDOMNode.
Thank you.
Upvotes: -1
Views: 3139
Reputation: 1075309
There are a couple of issues with the code you've found which mean I wouldn't use it as a starting point:
ReactDOM.findDOMNode
is generally poor practice, and the function is now deprecated. Using it just to hook up event handlers is unnecessary. Instead, use React's events instead, or at worst, a ref
on the top-level element.
It doesn't pass props
to super()
, which Component
subclasses are required to.
Instead, use React's events:
function ResizablePanels() {
const [isDragging, setIsDragging = useState(false);
const [panels, setPanels] = useState([300, 300]); // *** Only if they change during component lifecycle
const resizePanel = (evt) => {
// ...
};
const stopPanel = (evt) => {
// ...
};
return (
<div onMouseMove={resizePanel} onMouseUp={stopResize} onMouseLeave={stopResize}>
...
</div>
);
}
There I've used a div
as the top-level element, but that's just an example, it can be whatever you need it to be.
Upvotes: -2