Botir Ziyatov
Botir Ziyatov

Reputation: 518

How to React js event on scroll load other components

I have more components in one page. All pages loaded at the same time. But i want after scroll event loading next componentas.

HomePage.js:

render() {
        return (
            <section className="section1">
                    <Component1 />
            </section>          <section className="section2">                
                    <Component2 />                
            </section>
             <section className="section3">
                <Component3 />
             </section>
             <section className="section4">
                <Component4 />
             </section>
             <section className="section5">
                <Component5 />
            </section>
            <footer>
                <Footer />
            </footer>       
         );
    }

Have any idea? It is possible in react.

Thank you!

Upvotes: 1

Views: 7283

Answers (1)

ferronsays
ferronsays

Reputation: 134

You'll need to listen to a scroll event -- something like this:

componentDidMount() {
    window.addEventListener('scroll', this.handleScroll)
}

Keep in mind that you may want to listen to a scroll event on a specific element, and not the entire window. This will depend on your requirements for how/when these other components should load.

In handling that event, keep track of your scroll distance somehow.

handleScroll = (event) => {
    this.setState({
        scrollY: window.scrollY
    });
}

Note: Updating your state on every scroll event is probably over-kill though. I think the best approach would be to detect when the user has scrolled to the bottom and then conditionally load/render new components.

Then, in your render function, conditionally render additional components based on the value of your scroll distance. Again, you will likely need to include more sophisticated logic here based on your specific needs, but here is a rudimentary example based on scroll distance:

render() {
    let additionalComponents = null;

    if (this.state.scrollY > 1000) { //arbitrary amount
        additionalComponents = (
            <Component6 />
        );
    }

    return (
        <section className="section1">
                <Component1 />
        </section>          <section className="section2">                
                <Component2 />                
        </section>
         <section className="section3">
            <Component3 />
         </section>
         <section className="section4">
            <Component4 />
         </section>
         <section className="section5">
            <Component5 />
        </section>

        { additionalComponents }

        <footer>
            <Footer />
        </footer>       
     );
}

Upvotes: 4

Related Questions