Home HTML CSS JavaScript React Gamedatum.com
× Home HTML CSS JavaScript React Gamedatum.com

React Props and State


React components can receive data and configuration information through props. Props are passed to a component as an object and can be accessed using dot notation.

In React, props and state are used to manage data in a component. Props (short for properties) are read-only values that are passed down from a parent component to a child component. They are used to customize the behavior and appearance of a component. State, on the other hand, is a mutable data object that belongs to a component and can be changed by the component itself. It represents the current state of a component and is used to render the component dynamically based on user interactions, data fetching, or other events. By using props and state, React components can be built in a modular and reusable way, making it easier to manage complex user interfaces.

Here's an example of a functional component:

What is a React component

                     
                      
function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

<Greeting name="John" />


                                           
                                           
                

State is used to store data that can change over time. State is only available in class components and is updated using the setState method.

                     
                      
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increment
        </button>
      </div>
    );
  }
}