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>
It's difficult to tell from the code you added, but you might be simply missing this imperative in your constructor:
constructor( props ){
super( props );
this.handleScroll = this.handleScroll.bind(this)
}
more info: https://medium.freecodecamp.org/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With