Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

<div className='base-state' onClick={this.handleClick}>click here</div> 

The behaviour I am looking for is to add an extra class on click. My first idea was to try and add the class in the click handler function e.g.

handleClick : function(e) {    <add class "click-state" here> } 

I haven't been able to find any examples that do anything similar though, so I am fairly sure I am not thinking about this in the right way.

Can anyone point me in the right direction?

like image 616
Finglish Avatar asked Feb 26 '15 00:02

Finglish


People also ask

How do I add a className to a React component?

To pass class names as props to a React component:Pass a string containing the class names as a prop. Destructure the prop in the child component. Assign the class names to an element, e.g. <h2 className={className}>Content</h2> .

How do you toggle className in React?

To toggle class on click with React, we can set the className prop. to create the MyComponent component. In it, we have the isActive state. We set it with the setActive function in the toggleClass function.


1 Answers

The list of classes can be derive from the state of the component. For example:

var Component = React.createClass({   getInitialState: function() {     return {       clicked: false     };   },    handleClick: function() {     this.setState({clicked: true});   },    render: function() {     var className = this.state.clicked ? 'click-state' : 'base-state';     return <div className={className} onClick={this.handleClick}>click here</div>;   } }); 

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

like image 129
Felix Kling Avatar answered Oct 01 '22 08:10

Felix Kling