TripleTen Component State (React)

PHOTO EMBED

Sun Dec 17 2023 23:26:42 GMT+0000 (Coordinated Universal Time)

Saved by @Marcelluki

// User class component
class User extends React.Component {
  constructor(props) {
    super(props);

    // starting values for component's state
    this.state = {
      rating: 0,
    };
  }

  /*
   * event handlers: change the state
   */
  handleLike = () => {
    this.setState({ rating: 1 });
  };

  handleDislike = () => {
    this.setState({ rating: -1 });
  };

  // render the JSX structure
  render() {
    return (
      <div>
        <img
          src={`https://practicum-content.s3.us-west-1.amazonaws.com/web-code/react/moved_${this.props.id}.png`}
          width="75"
        />
        <p>{this.props.name}</p>
        <div className="rating">
          <button onClick={this.handleLike}>👍</button>
          {this.state.rating}
          <button onClick={this.handleDislike}>👎</button>
        </div>
      </div>
    );
  }
}

// the main app code
ReactDOM.render(
  <>
    <h2>My Imaginary Friends:</h2>
    <User id="1" name="Gregory" />
    <User id="2" name="James" />
    <User id="3" name="Allison" />
  </>,
  document.querySelector("#root")
); 
content_copyCOPY

Quite often, we need to store some data inside of our component that will change over the component's lifespan. Let's think of an example of this kind of data for our own component. How about a user rating? We want our users to be able to determine each other's reputation by using a "likes" and "dislikes" rating system. This data won't be passed down from props, but will be created and changed right inside of the component itself. To achieve our goal, we can use the state property and the setState() method, which are shared by all instances created using React class components:

https://tripleten.com/trainer/web/lesson/5d974c2e-872d-4984-8c5a-33caa7fe0ef0/task/dbe4f951-423f-4c6e-893b-91d635827c2a/