Comment toggler en React ? (un petit exemple)

08 avril 2016 / Marouen Mhiri / React

A great thing that belongs to the basics of React is the state of a component. So if you want your component to change it's "behavior", you may only need to do a "state change". Every time the state changes, React will try to render the component once again (if the state is explicitly used in the render method). So let's try to show this small example: (We want to change the color of CTA-Button on click event)

					
class Button extends React.Component {
	constructor(){
		super();
		this.handleClick = this.handleClick.bind(this);
		this.state = {
			active : false
		}
	}

	handleClick(e){
		e.preventDefault();
		e.stopPropagation();
		this.setState ({
		        active: !this.state.active
		});
	}

	render(){
		return (
			<a className={this.state.active?'active':'inactive'}
                           href="#"
                           onClick={this.handleClick}>
                                  Click me
                        </a>
		);
	}
}

ReactDOM.render(<Button/>,document.getElementById('mountNode'));
					
				

Well, is it simple? yes it is :-). The only thing to do was to keep the classname of the button changing depending on the state "active". If the "active" state is true so our class name will be "active", otherwise "inactive". The rest is done with css.

Check this running on jsFiddle.

Tags :

reacttoggle