Blog>
Snippets

State and Props in Class Components

Provide an example of how to pass props to a class component and use state within the component to maintain data.
class Greeting extends React.Component {
  constructor(props) {
    super(props);
    // Initialize state here
    this.state = { timesGreeted: 0 };
  }

  // Function to update state
  addGreeting() {
    this.setState((prevState) => ({
      timesGreeted: prevState.timesGreeted + 1
    }));
  }

  render() {
    return (
      <div>
        {/* Displaying the name prop and timesGreeted state */}
        <h1>Hello, {this.props.name}!</h1>
        <p>You have been greeted {this.state.timesGreeted} times.</p>
        {/* Button to invoke addGreeting method to update state */}
        <button onClick={() => this.addGreeting()}>Greet Me Again</button>
      </div>
    );
  }
}
This code defines a class component called Greeting that takes 'name' as a prop and utilizes a 'timesGreeted' state that tracks how many times the user has been greeted. When the button is clicked, the addGreeting method is called, which updates the timesGreeted state.
const App = () => (
  <div>
    {/* Passing the 'name' prop to the Greeting component */}
    <Greeting name="Chris" />
  </div>
);
This code shows a functional component called App that renders the Greeting component with a 'name' prop set to 'Chris'.