State and Props
In React, state and props allow us to manage data within components and pass data between components.
State
State is a JavaScript object that represents the current state of a component. It is used to store and manage data that can change over time.
To work with state in React, we can use the useState
hook. The useState
hook returns an array with two elements: the current state value and a function to update the state.
Here's an example of using state in a functional component:
1// Replace with relevant React code
2
3import React, { useState } from 'react';
4
5const Counter = () => {
6 const [count, setCount] = useState(0);
7
8 const handleIncrement = () => {
9 setCount(count + 1);
10 };
11
12 const handleDecrement = () => {
13 setCount(count - 1);
14 };
15
16 return (
17 <div>
18 <h1>Counter: {count}</h1>
19 <button onClick={handleIncrement}>Increment</button>
20 <button onClick={handleDecrement}>Decrement</button>
21 </div>
22 );
23};
24
25export default Counter;
In this example, we define a functional component called Counter
that uses the useState
hook to manage a count state. We have two buttons that increment and decrement the count when clicked.
Props
Props allow us to pass data from a parent component to a child component. They are read-only and cannot be modified by the child component.
To pass props to a child component, we include them as attributes when using the child component.
Here's an example of passing props to a child component:
1// Replace with relevant React code
2
3import React from 'react';
4
5const Greeting = (props) => {
6 return (
7 <div>
8 <h1>Hello, {props.name}!</h1>
9 <p>{props.message}</p>
10 </div>
11 );
12};
13
14export default Greeting;
In this example, we define a functional component called Greeting
that receives name
and message
props. We display the name and message in the component's UI.
State and props are fundamental concepts in React that allow us to build dynamic and reusable components. Understanding how to manage state and pass props between components is key to developing React applications.
Now it's your turn to practice by implementing a counter component that uses state and passing props to a child component called Greeting
that displays a customized greeting. Use the provided code examples as references for your implementation.
xxxxxxxxxx
// Replace with relevant React code
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const handleIncrement = () => {
setCount(count + 1);
};
const handleDecrement = () => {
setCount(count - 1);
};
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={handleIncrement}>Increment</button>
<button onClick={handleDecrement}>Decrement</button>
</div>
);
};
export default Counter;