Home

React this.state

Dynamic information is information that can change.

React components will often need dynamic information in order to render.
For example, imagine a component that displays the score of a basketball game.
The score of the game might change over time, meaning that the score is dynamic.
Our component will have to know the score, a piece of dynamic information, in order to render in a useful way.

There are two ways for a component to get dynamic information: props and state.
Besides props and state, every value used in a component should always stay exactly the same.

Unlike props, a component’s state is not passed in from the outside.
A component decides its own state.

You can take a look at w3schools document on React State Here

constructor() and super() are not unique to React.
The constructor() is a special method for creating and initializing objects created within a class.
Here you can see more from w3schools about...
constructor()
super()

Stateful Components are any component that has a state property.
Stateless Components are any component that does NOT have a state property.


Example...

import React from 'react';
import ReactDOM from 'react-dom';

const green = '#39D1B4';
const yellow = '#FFD712';

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      color: green
    };
    this.changeColor = this.changeColor.bind(this);
  }

  changeColor() {
    if (this.state.color == green) {
      this.setState({
          color: yellow})
    } else {
      this.setState({
          color: green})
    }
  }

  render() {
    return (
      <div style={{background:this.state.color}}>
        <h1>
          Change my color
        </h1>
        <button onClick={this.changeColor}>
          Change color
        </button>
      </div>
    );
  }
}

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

Top

Code Example Breakdown

Constructor

constructor(props) {
    super(props);
    this.state = {
        color: green
    };
    this.changeColor = this.changeColor.bind(this);
    this.myName = "Gary";
  }
For properties that are created inside the class we need the constructor & super as props means 'properties'.
As it is not specific to React I won't go in to these further.

this.state is where we need to specify any properties that are specific to this class and where the value of the property may change (and therefore re-render (re-draw) the page).

You can add properties where the value doesn't change (and does not force a render) by NOT adding them in the this.state, eg...
this.myName = "Gary";

I will expand on the
this.changeColor = this.changeColor.bind(this);
in the next pane.


Code Example Breakdown

Method

changeColor() {
    if (this.state.color == green) {
      this.setState({
          color: yellow})
    } else {
      this.setState({
          color: green})
    }
  }
To create a method in the class you need to, eg...
changeColor() { }
or, if you need parameters...
changeColor(param1, param2, etc...) { }

Note...
If you do not use arrow functions (=>), like you might do in JavaScript, eg...
changeColor = () => { }
but instead use it as described in this code example then you MUST bind it in the constructor function, eg...
this.changeColor = this.changeColor.bind(this);


BINDING

When creating a method/function in React that performs this.setState() like this, the .bind() makes React understand it is a method/function that will be using this.

See the w3schools document on bind Here
scroll down to the bind section.


So far I have found that the arrow function works/doesn't work in my coursework sometimes...it looks like how React is set to work (setup is different maybe?)
More on this when I get a chance to look in to it more.


Top

More on changeColor()

changeColor() {
    if (this.state.color == green) {
      this.setState({
          color: yellow})
    } else {
      this.setState({
          color: green})
    }
  }
Just a side comment
The code inside the changeColor() method could be shorter
I could have said...

changeColor() {
  const newColor = 
    this.state.color == green ? yellow : green;
  this.setState({color: newColor})
}
This way uses the Ternary Operator expression , eg...
(operator) ? value1 : value2
if operator is true then use value1 else use value2

changeColor() and this.state

changeColor() {
    if (this.state.color == green) {
                this.setState({
          color: yellow})
    } else {
                this.setState({
          color: green})
    }
  }
Once the properties have been set-up inside this.state you can change their values by, for example, in the changeColor() method.

Because the propertyis stored inside this.state in ordedr to change the property value you have to use the in-built setState method to do this, eg...

this.setState( {color: yellow} )

We need to put the property (or properties) inside curly braces just like we did when setting them up inside this.state {} in the constructor.
this.state = { color: green };

Note...
When dealing with multiple properties it would be, eg...
this.state = {
   color: green,
   name: "Gary",
   age: 21
};

this.setState( {
   color: yellow,
   name: "Bert",
   age: 29
});


but as setState() is a method we need the brackets ()'s

Top

this.setState() automatically calls render

this.setState() is actually two things:
this.setState(), immediately followed by .render()

Which is why you can’t call this.setState() from inside of the .render() method! this.setState() automatically calls .render().
If .render() calls this.setState(), then an infinite loop is created.


Double Curly Braces { {} }

render() {
    return (
      <div style={{background:this.state.color}}>
        <h1>
          Change my color
        </h1>
        <button onClick={this.changeColor}>
          Change color
        </button>
      </div>
    );
  }
NOTE that in the render method of the class we used double curly braces { {} } inside the <div> element.

This is because the command...
background:this.state.color
is a Javascript object
(and needs to be inside {}'s)...

...And to embed this object into JSX it also needs to be inside its own set of curly braces {}'s

Therefore the first set of {}'s represents one instruction (a JSX instruction)
and the second set of {}'s represents another instruction (Javascript instruction).
<div style={ {background:this.state.color} }>

Top