Skip to content Skip to sidebar Skip to footer

How To Add Or Remove A Classname On Event In Reactjs?

I am quite new to React and I am struggling a little with converting my thinking from standard js. In my react component I have the following element:
: 'base-state'; return<divclassName={className}onClick={this.handleClick}>click here</div>; } });

Calling this.setState will trigger a rerender of the component.

Solution 2:

You could use just a Vanilla JS (event.target and classList):

handleClick = event => event.target.classList.add('click-state');

render() {
  return<divclassName="base-state"onClick={this.handleClick}>Click here</div>;
}

BUT don't do that!

React should handle changes in the DOM, so rely on modifying CSS classes via React.

Event.target

Element.classList

React / Styling and CSS

Solution 3:

You could set click state in the click handler function and use it to set the class name conditionally using a template literal.

If you're using a function component, you can do it this way using the useState hook:

const [clicked, setClicked] = useState(false);

<divclassName={ `base-state ${clicked && 'click-state'}` } onClick={ () => setClicked(true) }>click here</div>

Solution 4:

Every above solution is about setting className='click-state' on click but not removing class if already exist on double click. If someone is using a functional component, this behaviour can be achieved by using useState hook and some conditional statement.

const [clicked, setClicked] = useState('');

consthandleClick = () => {
  clicked ? setClicked('') : setClicked('base-state click-state');
};

<divclassName={clicked || 'base-state' } onClick={handleClick}>click here</div>

Solution 5:

Well to do this you can use Vanilla javascript but that might not be standard practice in react.

So what you can do is here:

let className = 'base-state';
  if (this.props.isActive) {
    className += ' click-state';
  }
  return<spanclassName={className}>Menu</span>
}

to make it easier you can use an npm package called classnames

You can visit Npm package through this link. for more references, you can visit the official React-docs

Post a Comment for "How To Add Or Remove A Classname On Event In Reactjs?"