React Holiday

Day 7: State of mind

Being sexy is all about attitude… It’s a state of mind.
— Amisha Patel

One of the special powers of class components is their ability to hold state.

With state, you get interactivity. No state, no interactivity. So component state isn’t just a feature, it’s the feature.

How I do dat state hawtnez?

Start with an initial state. Do this in the constructor of your class components.

class MyStateOfMind extends React.Component {
  constructor() {
    super();
    this.state = { sexy: true }
  }
  ...

In create-react-app projects, use this ESNext syntax to avoid the constructor noise.

class MyStateOfMind extends React.Component {
  state = { sexy: true }
  ...

Back to Claps

Let’s add a clapCount state to the ClapsCounter we worked on yesterday.

class ClapCounter extends React.Component {
  state = { clapCount: 0 }
  
  render() {
    return (
      <div>
        <button
          type="button"
          onClick={() =>
            alert(this.state.clapCount + 1 + " claps")
          }
        >
          {this.state.clapCount}{' '}👏
        </button>
        <i> be the first to clap</i>
      </div>
    );
  }
}

Stay sexy, nerds

Now you know how to initialize state and your state of mind will always be sexy.

As for our clapCount state, it’ll be changing tomorrow…

Tinker with it

Use the workspace below and play with state.

  • Change the initial state from 0 to 100. Does the alert read 101 claps?
  • Add more state properties. Try strings, numbers, function expressions, whatever you want.