Languages
[Edit]
EN

React - use state in a component (class component)

0 points
Created by:
Dirask Community
6240

In this article, we would like to show you how to use state in React.

Below example presents a class component with state object where we store property values that belong to the component. 

We refer to the state object by using this.state.propertyname (in our case this.state.animal).

Note: When the state changes, the component re-renders.

Runnable example:

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from react';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      animal: 'dog',
      color: 'black'
    };
  }
  render() {
    return (
      <div>
        <p>
          animal: = {this.state.animal}, 
          color: = {this.state.color}
        </p>
      </div>
    );
  }
}

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Note:

Go to this article to see functional component example.

ReactJS

React - use state in a component (class component)
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join