⚠️ This lesson is retired and might contain outdated information.

Manage React Component State with setState

Joe Maddalone
InstructorJoe Maddalone
Share this video with your friends

Social Share Links

Send Tweet
Published 11 years ago
Updated 2 years ago

State is used for properties on a component that will change, versus static properties that are passed in. This lesson introduces you to updating state through a simple text input and displaying that in the browser.

[00:00] Unlike props, which are a collection of values that are meant to be passed into our component as static value, it's not meant to be changed by our component. State represents a collection of values that is meant to be managed, as well as updated by our component.

[00:14] To get us started using state, I'm going to setup a constructor method here, and the first thing I'm going to do is, I'm going to call super. This is going to give the keyword "this" the context within our component, rather than its parent class React.Component.

[00:29] Here, we're going to set up, this.state equal to an object, I'm going to create a key called "text," I'm going to say, "This is the state text."

[00:39] To use state within our JSX, we interpolate it just like we do this.props, but this time, we're going to say, this.state, and then, the key that we're looking for, in this case, it's txt. We can see in the browser there, we get this is the state text.

[00:55] Again, this is meant to be managed and updated by our component. I'm going to create a method here called "update," that takes in an event. It's important to note this is not a part of the specification, this is just a custom method on our component.

[01:08] I'm simply going to call this.setState, we're going to pass in a new object, with a key of text, and I'm going to get a new value off of that event, I'm going to say e.target.value.

[01:21] Now to get that working, I'm going to wrap this JSX in a parent node, we only have a single node being delivered by our render method. I'm going to create an input here, and on its onchange event, I'm going to call this.update, the custom method that we created. I'm going to go ahead and bind that with a context of this.

[01:43] When we run that, we've got our default state text here, and when we type in this, this is the new text, we can see that our state is in fact being updated, and every time we call this.setState, our render method is being rerun. It's important to note here that, the call of this.setState only overwrites the values that we actually send into it.

[02:07] If I created another value in our state for cat, and its default is zero. We'll go ahead and output that right here, after the text value. I'll just say cat. Save that. We can see that in the browser, when we change our state, the value for cat and our state is not lost, only the value for text is updated.

Richard
Richard
~ 9 years ago

Can you explain why the need to use this.update.bind(this) in the onChange attribute?

Joel Hooks
Joel Hooks
~ 9 years ago

Can you explain why the need to use this.update.bind(this) in the onChange attribute?

Previously with React.createClass you would get autobinding. When you use es6 classes, this is no longer the case, so you need to explicitly bind the this scope of event handler functions. People will also do this in the constructor or through a more "es7" style property binding.

    constructor(props) {
        super(props);
        this.update = this.update.bind(this);
    }
MyComponent extends React.Component {
      
    update = () => this. update();

    render() {
    // ...
Irvin Waldman
Irvin Waldman
~ 9 years ago

Which is the preferred way?

jeff
jeff
~ 9 years ago

I would love a short tutorial about this.

Somsubhra  Ghosh
Somsubhra Ghosh
~ 9 years ago

I was trying to use ES7 style and was getting a syntax error..Is there anything I am doing incorrectly

class App extends React.Component { ... update = () => this.updateEnteredText(); updateEnteredText(e){ ... } render() { .....

Rajeev Mishra
Rajeev Mishra
~ 9 years ago
_bind(...methods) {
  methods.forEach( (method) => this[method] = this[method].bind(this) );
 }

I am doing it this way and then inside constructor this._bind('methodName1','methodName2');

Simon Sturmer
Simon Sturmer
~ 9 years ago

Could I please ask which editor (Atom?) and what plugins you are using? It is like magic and I'd love to make those efficiency gains!

Pete
Pete
~ 9 years ago

I had some trouble with this because the code in the video does not match the code under Code. I was able to resolve it by adding:

import ReactDOM from 'react-dom';

and

changing:

export default App

to

ReactDOM.render(<App />, document.getElementById('app'));

The JSBin HTML file has script links to fb.me for react and react-dom, so that it does work there, but that is not part of the course lesson.

In further investigation, I found on the github repo for lesson 4 that main.js had been returned to its original state. In one of the earlier lessons, he deletes several lines, but never indicates in subsequent lessons that he put them back.

Tommy
Tommy
~ 8 years ago

Thank you for this, this worked for me.

Glenn
Glenn
~ 7 years ago

I've got the code for this part working, however in the browser console I see

B:\Projects\JS\react-learning\node_modules\react-error-overlay\lib\overlay.js:66
Uncaught TypeError: Cannot read property 'error' of undefined
 at renderErrorByIndex (B:\Projects\JS\react-learning\node_modules\react-error-overlay\lib\overlay.js:66)
at switchError (B:\Projects\JS\react-learning\node_modules\react-error-overlay\lib\overlay.js:86)
at shortcutHandler (B:\Projects\JS\react-learning\node_modules\react-error-overlay\lib\overlay.js:145)
at keyHandler (B:\Projects\JS\react-learning\node_modules\react-error-overlay\lib\effects\shortcuts.js:17)

Not sure what is causing this. My code looks like the following:

import React from 'react';
import PropTypes from 'prop-types'; // React.PropTypes is deprecated apparently

class App extends React.Component {
    constructor(){
        super();
        this.state =  {
            txt: 'this is dynamic text'
        }
    }

    update( e ){
        this.setState({txt: e.target.value})
    }

    render() {
        let txtProp = this.props.txt;
        let numProp = this.props.cat;
        return ( 
            <div>
                <h1>Hello World - {txtProp} + {numProp} </h1>
                <input type="text" onChange={this.update.bind(this)}/>
                <h2>{this.state.txt}</h2>
            </div>
        )
    }
}

App.propTypes = {
    txt: PropTypes.string,
    cat: PropTypes.number.isRequired
}

App.defaultProps = {
    txt: "default text"
}

// const App = () => <h1>Hello Stateless</h1>

export default App
Markdown supported.
Become a member to join the discussionEnroll Today