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

后端 未结 2 813
我寻月下人不归
我寻月下人不归 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: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 (
            
    {this.state.elementToScroll1 &&
    First element
    }
    {this.state.elementToScroll2 &&
    Second element
    }
    ); } } 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.

提交回复
热议问题