I'm using ReactJS with NextJS. When I'm trying to set a ref
, my console returns me undefined
, how it is possible? How remedy to this difficulty? I have tried to read some propositions on the web but without success.
Here my snippet:
componentDidMount() {
this.myRef = React.createRef();
window.addEventListener('scroll', this.handleScroll, { passive: true })
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll)
}
handleScroll(e) {
e.preventDefault();
// let offsetTop = this.myRef.current.offsetTop;
// here I'm trying just a console.log to preview the value
// otherwise my program will just crash
console.log("I'm scrolling, offsetTop: ", this.myRef)
}
render() {
return (
<div className={style.solution_container_layout} >
<div ref={this.myRef} className={style.solution_item}>
Any hint would be great, thanks
The current
property of the object returned from createRef
is set on the first render, so if you create it in the componentDidMount
after the component has been rendered it will not be set.
You also have to bind the handleScroll
method, or this
will not be what you expect.
Example
class App extends React.Component {
myRef = React.createRef();
componentDidMount() {
window.addEventListener("scroll", this.handleScroll, { passive: true });
}
componentWillUnmount() {
window.removeEventListener("scroll", this.handleScroll);
}
handleScroll = () => {
console.log("I'm scrolling", this.myRef.current);
};
render() {
return <div ref={this.myRef} style={{ height: 1000 }}> Scroll me </div>;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>