Props and State
In React, props and state are two fundamental concepts that allow you to manage data and control the behavior of your components.
Props
Props (short for properties) are used to pass data from a parent component to a child component. They are like function arguments or variables passed to a function.
An example of using props in a React component:
1import React from 'react';
2
3function Greeting(props) {
4 return (
5 <div>
6 <h1>Hello, {props.name}!</h1>
7 <p>{props.message}</p>
8 </div>
9 );
10}
11
12export default Greeting;
In this example, the Greeting
component accepts name
and message
as props and renders them in the JSX code using curly braces.
To use the Greeting
component and pass values to its props, you can do the following:
1import React from 'react';
2import Greeting from './Greeting';
3
4function App() {
5 return (
6 <div>
7 <Greeting name="John" message="Welcome to React!" />
8 </div>
9 );
10}
11
12export default App;
The Greeting
component is imported and used in the App
component, and the name
and message
props are set with values.
Props are read-only and should not be modified directly from the child component. If you need to change the value of a prop, you should do so by updating the data from the parent component.
State
State is used to manage data within a component. It represents the current state of the component and can be changed over time.
To use state in a class component, you need to define a constructor
and initialize the state object with the initial values. Here's an example:
1import React, { Component } from 'react';
2
3class Counter extends Component {
4 constructor(props) {
5 super(props);
6 this.state = {
7 count: 0
8 };
9 }
10
11 render() {
12 return <div>{this.state.count}</div>;
13 }
14}
15
16export default Counter;
In this example, the Counter
component has a count
property in its state object, which is initially set to 0. The value of count
is rendered in the JSX code.
To update the state, you can use the setState
method provided by React. Here's an example of incrementing the count:
1import React, { Component } from 'react';
2
3class Counter extends Component {
4 constructor(props) {
5 super(props);
6 this.state = {
7 count: 0
8 };
9 }
10
11 incrementCount() {
12 this.setState({
13 count: this.state.count + 1
14 });
15 }
16
17 render() {
18 return (
19 <div>
20 <div>{this.state.count}</div>
21 <button onClick={() => this.incrementCount()}>Increment</button>
22 </div>
23 );
24 }
25}
26
27export default Counter;
In this example, a button is added to the component, and when clicked, it calls the incrementCount
method, which updates the state by incrementing the count
value.
Props and state are essential concepts in React, and understanding how they work is crucial for building dynamic and interactive components.
xxxxxxxxxx
import React from 'react';
function Greeting(props) {
return (
<div>
<h1>Hello, {props.name}!</h1>
<p>{props.message}</p>
</div>
);
}
export default Greeting;