Skip to content Skip to sidebar Skip to footer

How To Toggle Class On Mousedown/mouseup In React Component?

I'm trying to toggle a class in a react component where if a user has his mouse down on a button, then it'll add a class to that button and when the user has his mouseup, then it r

Solution 1:

this will not be an HTML element, but React Object instance.

I would try more reactive way to achieve this and used state:

classButtonextendsReact.Component {
  constructor(props) {
    super(props);
    this.state = {
      isDown: false
    };
  }

  toggleClass() {
    this.setState(prevState => ({ isDown: !prevState.isDown }));
  }

  render() {
    return (
      <buttonclassName={this.state.isDown ? "btnDown" : ""}
        onMouseDown={e => this.toggleClass(e)}
        onMouseUp={e => this.toggleClass(e)}
        {...this.props}
      />
    );
  }
}

exportclassButtonsextendsReact.Component {
  render() {
    return (
      <divclassName="btn-wrap"><Buttonvalue="1">1</Button><Buttonvalue="2">2</Button>
        ....
      </div>
    );
  }
}

Solution 2:

You can make your own Button component

classButtonextendsReact.Component {
  constructor(props) {
    super(props);
    this.state = {
      isDown: false
    };
  }

  toggleClass() {
    this.setState(prevState => ({ isDown: !prevState.isDown }));
  }  

  render() {
    const className = `${this.state.isDown ? "btnDown" : ""}`;
    return<buttonclassName={className}onMouseDown={e => this.toggleClass(e)} value={this.props.value} {...this.props}>{this.props.children}</button>
  }
}

And then use those instead of the html button -

<divclassName="btn-wrap"><Buttonvalue = '1'>1</Button><Buttonvalue = '2'>2</Button><Buttonvalue = '3'>3</Button><Buttonvalue = '+'onClick={e => console.log('+ clicked')}>3</Button><Buttonvalue = '-'onClick={e => console.log('- clicked')}>3</Button></div>

Solution 3:

Instead of using this inside toggleClass, use the event object :

classButtonsextendsReact.Component{
    toggleClass(e) {
      if(e.target.classList.contains('btnDown')) {
        e.target.classList.remove('btnDown');
      } else {
        e.target.classList.add('btnDown');
      }
    }

    render() {
      return (
        <div className="btn-wrap">
          <button onMouseDown={(e) => this.toggleClass(e)} onMouseUp={(e) => this.toggleClass(e)} value = '1' >1</button>
          <button onMouseDown={(e) => this.toggleClass(e)} onMouseUp={(e) => this.toggleClass(e)} value = '2' >2</button>
          <button onMouseDown={(e) => this.toggleClass(e)} onMouseUp={(e) => this.toggleClass(e)} value = '3' >3</button>
        </div>
      )
    }
}

The css was taken from @Tomasz Mularczyk's answer.

jsfiddle

Solution 4:

I rewrote your code a little bit, it should work properly now:

classButtonsextendsReact.Component {

     constructor(props) {
         super(props);
         this.state = {
         isDown: null
      };

  }

  pressButton = (i) => {
    this.setState({ isDown: i });
  };
  releaseButton = () => {
    this.setState({ isDown: null });
  };

  render() {
    const { isDown } = this.state;
    const buttons = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, '+', '-'];

    return (
      <divclassName="btn-wrap">
        {buttons.map((button, i) => (
          <buttonclassName={`${isDown === i ? 'btnDown' : ''}`}
            onMouseDown={this.pressButton.bind(undefined,i)}
            onMouseUp={this.releaseButton}value={button}
          >
            {button}
          </button>
        ))}
      </div>
    )
  }
}

ReactDOM.render(
  <Buttons />,
  document.getElementById('container')
);`

Post a Comment for "How To Toggle Class On Mousedown/mouseup In React Component?"