ReactJS - ref returns “undefined”












1















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










share|improve this question



























    1















    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










    share|improve this question

























      1












      1








      1








      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










      share|improve this question














      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







      javascript reactjs position ref






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 24 '18 at 19:25









      WebwomanWebwoman

      616528




      616528
























          2 Answers
          2






          active

          oldest

          votes


















          2














          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>








          share|improve this answer
























          • thanks, but seems the relative position of my element to the viewport top - with scrollTop - seems to remain fixed, like there is one measure then no other is done, do you know maybe what happens please

            – Webwoman
            Nov 24 '18 at 19:56











          • @Webman Since the element doesn't scroll its scrollTop doesn't change. You might want ` window.pageYOffset` instead.

            – Tholle
            Nov 24 '18 at 20:00



















          1














          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






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53461630%2freactjs-ref-returns-undefined%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            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>








            share|improve this answer
























            • thanks, but seems the relative position of my element to the viewport top - with scrollTop - seems to remain fixed, like there is one measure then no other is done, do you know maybe what happens please

              – Webwoman
              Nov 24 '18 at 19:56











            • @Webman Since the element doesn't scroll its scrollTop doesn't change. You might want ` window.pageYOffset` instead.

              – Tholle
              Nov 24 '18 at 20:00
















            2














            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>








            share|improve this answer
























            • thanks, but seems the relative position of my element to the viewport top - with scrollTop - seems to remain fixed, like there is one measure then no other is done, do you know maybe what happens please

              – Webwoman
              Nov 24 '18 at 19:56











            • @Webman Since the element doesn't scroll its scrollTop doesn't change. You might want ` window.pageYOffset` instead.

              – Tholle
              Nov 24 '18 at 20:00














            2












            2








            2







            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>








            share|improve this answer













            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>








            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>





            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>






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 24 '18 at 19:39









            TholleTholle

            38.1k54264




            38.1k54264













            • thanks, but seems the relative position of my element to the viewport top - with scrollTop - seems to remain fixed, like there is one measure then no other is done, do you know maybe what happens please

              – Webwoman
              Nov 24 '18 at 19:56











            • @Webman Since the element doesn't scroll its scrollTop doesn't change. You might want ` window.pageYOffset` instead.

              – Tholle
              Nov 24 '18 at 20:00



















            • thanks, but seems the relative position of my element to the viewport top - with scrollTop - seems to remain fixed, like there is one measure then no other is done, do you know maybe what happens please

              – Webwoman
              Nov 24 '18 at 19:56











            • @Webman Since the element doesn't scroll its scrollTop doesn't change. You might want ` window.pageYOffset` instead.

              – Tholle
              Nov 24 '18 at 20:00

















            thanks, but seems the relative position of my element to the viewport top - with scrollTop - seems to remain fixed, like there is one measure then no other is done, do you know maybe what happens please

            – Webwoman
            Nov 24 '18 at 19:56





            thanks, but seems the relative position of my element to the viewport top - with scrollTop - seems to remain fixed, like there is one measure then no other is done, do you know maybe what happens please

            – Webwoman
            Nov 24 '18 at 19:56













            @Webman Since the element doesn't scroll its scrollTop doesn't change. You might want ` window.pageYOffset` instead.

            – Tholle
            Nov 24 '18 at 20:00





            @Webman Since the element doesn't scroll its scrollTop doesn't change. You might want ` window.pageYOffset` instead.

            – Tholle
            Nov 24 '18 at 20:00













            1














            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






            share|improve this answer




























              1














              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






              share|improve this answer


























                1












                1








                1







                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






                share|improve this answer













                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







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 24 '18 at 19:38









                NiRRNiRR

                1,97411943




                1,97411943






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53461630%2freactjs-ref-returns-undefined%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Create new schema in PostgreSQL using DBeaver

                    Deepest pit of an array with Javascript: test on Codility

                    Costa Masnaga