1.

What is state in React?

Answer»

When we want to change the data inside a Component we use state. It is one of the most important and difficult concepts in React to understand.

We need to initialise the state first. After that, we need to change the state. Consider the updated code for App.js from our JSX example(Question 5)

import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component {  constructor(){    super();    this.state = {      spinLogo: true    };    this.updateLogo = this.updateLogo.bind(this);  }  updateLogo() {    this.setState({      spinLogo: !this.state.spinLogo    });  }  render() {    return (      <DIV className="App">        <header className="App-header">        { this.state.spinLogo === true ?          <img src={logo} className="App-logo" alt="logo" /> :          <a href="https://reactjs.org" target="_blank">            Learn React          </a>        }        <button onClick={this.updateLogo}>Click me!</button>        </header>      </div>    );  } } export default App;

Initializing State
To initialize the state, simply set this.state in the constructor() method of the class. Our state is an object which in our case only has one key called spinLogo. Before we set the state, we have to call super() in the constructor. This is because this is uninitialized before super() has been called.

In our render method, we are CHECKING the value of spinLogo by this.state.spinLogo. It is initially true, so the logo will be displayed.

Now, we have a button which has an EVENT listener onClick. When we click the button it runs the function updateLogo() and we change the state.

Changing the state

To modify the state, simply call this.setState(), passing in the NEW state object as the argument. We’ll do this inside a method which we’ll call updateLogo.  So, here we change the value of updateLogo to the opposite of it. Initially, it was true, so we make it FALSE.

One important concept in React is that whenever we call this.setState(), it re-renders the Component. So, this time when the ternary operator checks the value of this.state.spinLogo, it is false. So, it displays the link. Click the button again and it will show the logo.



Discussion

No Comment Found