If you think you need JQuery in your React app you’re doing it wrong

React is a great library for making changes to the DOM. There are lots of good features about React that make it easy to modify elements. Let’s take a look at a common use case in manipulating the DOM and see how it’s done in React.

Adding/Removing a class name

Say we have a part of our DOM that looks like this:

<div class="container">
<button id="someButton">Click Me!</button>
<div id="someElement">I'm an element</div>
</div>
$(document).ready(function(){
$('#someButton').on('click',function(){
if($('#someElement').hasClass('clicked')){
$('#someElement').removeClass('clicked');
}else{
$('#someElement').addClass('clicked');
}
});
});
var ExampleComponent = React.createClass({
getInitialState : function(){
return ({isClicked : false})
},
handleClick : function(){
this.setState({isClicked : !this.state.isClicked});
},
render: function() {
var someElementClass = this.state.isClicked ? 'clicked' : '';
return(<div className="container">
<div id="someElement" className={someElementClass}>
I'm an element
</div>
<button id="someButton" onClick={this.handleClick}>
Click me!
</button>
</div> );
}
});
ReactDOM.render(<ExampleComponent />,document.getElementById('content'));
  1. React components have a function called “getInitialState”. This does exactly what the function name would imply — it sets the initial state of the component. We can throw any sort of variable we want in there and access it via this.state. In this particular component, we’ve used a isClicked boolean to determine whether or not the button has been clicked.
  2. The handleClick function is where all the action happens. In this function , another React component function gets called — this.setState(). This is the “magic” function in React that allows you to update and modify your app. Updating this.state directly is BAD — don’t do it, just don’t. Your app will be unhappy and your users will have sad faces while trying to use your app. The only way to change this.state is to call the this.setState() function. When this function is called, a re-rendering of the virtual DOM happens and any changes that need to be made happen in the real DOM.

Editor of http://newsletter.fullstackreact.com, fan of all things React

Editor of http://newsletter.fullstackreact.com, fan of all things React