1

Got a small script coded which increments left or right by 100px when clicking on the previous and next buttons.

Was wondering if there was a way to make the script stop increasing the value once it reaches a certain point (let's say -500px or +500px for example).

constructor(props) {
        super();

        this.state = {
            bgColor: 0
        };
        this.handleClickRight = this.handleClickRight.bind(this);
        this.handleClickLeft = this.handleClickLeft.bind(this);
    }

    handleClickRight(e) {
        e.preventDefault();
        this.setState({
            bgColor: this.state.bgColor - 100
          })
      }

      handleClickLeft(e) {
        e.preventDefault();
        this.setState({
            bgColor: this.state.bgColor + 100
          })
      }

    render() {
        return (
            <div>

                <div className="slider-controls">
                    <a href="#" className="slider-control prev" onClick={this.handleClickLeft}>Prev</a>
                    <a href="#" className="slider-control next" onClick={this.handleClickRight}>Next</a>
                </div>

1 Answer 1

3

You might use Math.max and Math.min when setting the state. Also check that the value is not already at the minimum or maximum first, to avoid unnecessary re-rendering:

handleClickRight(e) {
  e.preventDefault();
  const { bgColor } = this.state;
  if (bgColor !== -500) this.setState({
    bgColor: Math.max(bgColor - 100, -500)
  })
}

handleClickLeft(e) {
  e.preventDefault();
  const { bgColor } = this.state;
  if (bgColor !== 500) this.setState({
    bgColor: Math.min(bgColor + 100, 500)
  })
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thats awesome! Works perfect and clean. Thanks so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.