D
D
Daniil Sugonyaev2018-09-19 17:52:51
JavaScript
Daniil Sugonyaev, 2018-09-19 17:52:51

How to make an up/down arrow appear/disappear in React?

Unexpectedly, I encountered such a problem. How to do a banal thing in React - when a certain indent from the top of the page is reached, an "up" arrow appears. That is, it is clear that it is possible to conditionally update the state, but how can it be implemented without constant re-rendering of the dom?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-09-19
@coolswood

class ArrowUp extends Component {
  state = {
    isVisible: false,
  };

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

  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
  }

  handleScroll = () => {
    if (window.scrollY >= SOME_VALUE  && !this.state.isVisible) {
      this.setState({ isVisible: true });
    } else if (window.scrollY < SOME_VALUE && this.state.isVisible) {
      this.setState({ isVisible: false });
    }
  };

  render() { /* ... */ }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question