ReactJS: Updating state

We have state in our component. And we can call this.setState from a click listener to update that state. When we update the state the component with effecticently (using virutaldom) redraw itself and any sub components.

this.setState takes a object as argument and its values relate to the property names in your state. It updates them.

We can call this from a onClick attribute on a HTML tag. The onClick's value is within curly bracked and the javascript is within: onclick={() => console.log("i am some javascript")}

We will change our style in our div object so it changes based on a clicked variable in our state.

    <script src=""></script>
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>
    <div id="root"></div>
  <script type="text/babel">

    class Hello extends React.Component {
      constructor(props) {
        this.state = {
          clicked: false,
      render() {
        return (
          <div style={{display: "flex", flexDirection: "row"}}>
            <div style={{color: (this.state.clicked) ? "lightgreen" : "blue" }}>Hello {}!</div>
            <button onClick={() => this.setState({clicked: true})}>on acid</button>

        <Hello name="Davey dave dave" />
        <Hello name="Chris" />
        <Hello name="Ahmed" />
        <Hello name="Peter" />

Edit on github
comments powered by Disqus
Click me