Languages
[Edit]
EN

React - use state in a component (class component)

0 points
Created by:
Violetd
835

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.

Alternative titles

  1. React - how to use state (class component)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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