use state in react in javascript

To use state in React, you first need to define a state object in your component's constructor function. The state object can contain multiple key-value pairs, where each key represents a particular piece of data that you want to store and render.

index.tsx
import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      message: "Hello World",
      isShowing: false
    };
  }
  // ...
}
232 chars
14 lines

Once you have defined the state object, you can access it and render its values in your component's JSX by using curly braces { }.

index.tsx
class MyComponent extends Component {
  // ...
  render() {
    return (
      <div>
        <h1>{this.state.message}</h1>
        <p>{this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increase Count
        </button>
      </div>
    );
  }
}
306 chars
15 lines

To update the state object and trigger a re-render of the component, you need to use the setState method. This method takes an object as an argument, where each key corresponds to a state value that you want to update.

index.tsx
class MyComponent extends Component {
  // ...
  handleClick = () => {
    this.setState({ isShowing: !this.state.isShowing });
  };

  render() {
    return (
      <div>
        {this.state.isShowing && <p>{this.state.message}</p>}
        <button onClick={this.handleClick}>
          {this.state.isShowing ? "Hide Message" : "Show Message"}
        </button>
      </div>
    );
  }
}
389 chars
18 lines

In the above example, the handleClick function updates the isShowing state value by toggling its value each time the button is clicked. This in turn will trigger a re-render of the component, and conditionally render the message value based on the current state.

gistlibby LogSnag