ReactJS how to render a component only when scroll down and reach it on the page?

后端 未结 2 791
我寻月下人不归
我寻月下人不归 2020-12-19 05:03

I have a react component Data which includes several charts components; BarChart LineChart ...etc.

When Data comp

相关标签:
2条回答
  • 2020-12-19 05:42

    You have at least three options how to do that:

    1. Track if component is in viewport (visible to user). And then render it. You can use this HOC https://github.com/roderickhsiao/react-in-viewport

    2. Track ‘y’ scroll position explicitly with https://react-fns.netlify.com/docs/en/api.html#scroll

    3. Write your own HOC using Intersection Observer API https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

    To render component you may need another HOC, which will return Chart component or ‘null’ based on props it receives.

    0 讨论(0)
  • 2020-12-19 05:53

    you can check window scroll position and if the scroll position is near your div - show it. To do that you can use simple react render conditions.

    import React, {Component} from 'react';
    import PropTypes from 'prop-types';
    
    class MyComponent extends Component {
    constructor(props){
        super(props);
    
        this.state = {
            elementToScroll1: false,
            elementToScroll2: false,
        }
    
        this.firstElement = React.createRef();
        this.secondElement = React.createRef();
    }
    componentDidMount() {
        window.addEventListener('scroll', this.handleScroll);
    }
    
    componentWillUnmount() {
        window.removeEventListener('scroll', this.handleScroll);
    }
    handleScroll(e){
        //check if scroll position is near to your elements and set state {elementToScroll1: true}
        //check if scroll position is under to your elements and set state {elementToScroll1: false}
    }
    render() {
        return (
            <div>
                <div ref={this.firstElement} className={`elementToScroll1`}>
                    {this.state.elementToScroll1 && <div>First element</div>}
                </div>
                <div ref={this.secondElement} className={`elementToScroll2`}>
                    {this.state.elementToScroll2 && <div>Second element</div>}
                </div>
            </div>
        );
    }
    }
    
    MyComponent.propTypes = {};
    
    export default MyComponent;
    

    this may help you, it's just a quick solution. It will generate you some rerender actions, so be aware.

    0 讨论(0)
提交回复
热议问题