learnreact.com is moving to school.reactpatterns.com. Get 50% off while we move.

Learn React

Learn React | <!-- -->Essetial React<!-- --> > <!-- -->setState - object form

Essetial React

setState - object form

Now we need a way of setting state. To do that, I’m going to make a few changes here. This should really be a button. This is kind of taking the shape of a button, so let’s change that now to be so. Now that has the nice appearance of a button. Let’s make this actually show the current number of claps with a clap emoji, so that we know that if we hit it, we’re going to get some clasp. That’s starting to look right. All buttons should have a type. This one is a button, not a submit or anything like that. So now we have our button. That seems to be right. It’s displaying this current number of claps. Unfortunately it’s not updating because we’re really just alerting the new button number, we’re not setting it. To set state we use a function called this.setState. It’s a magic functions that we get by extending React component. When we call it, we’re going to call it with the same shape of our component state, but we want to update it. Now again, I’m hard coding this value, but just to show you this simple form of, if I know the value that I want, I can pas it in in a new object that replaces this state, so there’s a nice symmetry there. This is the object form of a call to setState, so we’re calling setState with an object hta gets merges with this object, or in our cause is going to replace that zero with a hard coded one. It goes from zero to one, but no further. This is great when you know the exact state that you need to replace this state, but it’s not great when we want to update this from the previous state. Learn how to handle that next.



Keep in touch!

Get notified of new React content and resources

    We respect your privacy. Unsubscribe at any time.