Props and State in React
Props and state are two important concepts in React. They are used to manage the data and behavior of a React component.
Props
(short for "properties") are used to pass data from a parent component to its child components. Props are read-only and cannot be changed within the child component. They are essentially arguments that are passed to the child component.
Here's an example of using props in React:
const Greeting = (props) => {
return <h1>Hello, {props.name}!</h1>;
};
ReactDOM.render(
<Greeting name="John" />,
document.getElementById("root")
);
In this example, the Greeting
component accepts a name
prop, which is passed in from the parent component when the Greeting
component is rendered.
State
, on the other hand, is used to manage the data and behavior of a component that can change over time. Unlike props, state can be changed within a component. The state of a component should be managed in the most parent component that needs to access it, and it should be passed down to child components as props.
Here's an example of using state in React:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
ReactDOM.render(
<Counter />,
document.getElementById("root")
);
In this example, the Counter
component has a state with a single property, count
, which starts at 0. The increment
method is used to update the state whenever the button is clicked.
To summarize, props are used to pass data from a parent component to its child components, while state is used to manage the data and behavior of a component that can change over time.
Leave a Comment