State can be created and managed in functional components using the useState
hook, or in class components using the setState
method.
Props, short for properties, are a way to pass data from a parent component to a child component. Props are read-only, meaning they cannot be modified by the child component. Instead, the child component uses props to determine how to render itself.
Props are passed to a component as attributes in JSX, and they can be accessed in the component as a JavaScript object.
By using state and props, React allows us to create modular and reusable components that can be easily composed to build complex user interfaces.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}
In this example, we use state to store the count value of the counter component. Whenever the button is clicked, the handleClick
function is called and it updates the count state by incrementing the value by 1. This causes the component to re-render, displaying the updated count value.
2. User Component using Props:
import React from 'react';
function User(props) {
return (
<div>
<h1>{props.name}</h1>
<p>{props.email}</p>
</div>
);
}
In this example, we use props to pass user data to the User
component. The name
and email
data are passed to the component as props, and they are rendered inside the component. This allows us to reuse the User
component with different user data.
3. Input Component using State:
import React, { useState } from 'react';
function Input() {
const [text, setText] = useState('');
function handleChange(event) {
setText(event.target.value);
}
return (
<div>
<input type="text" value={text} onChange={handleChange} />
<p>You typed: {text}</p>
</div>
);
}
In this example, we use state to store the value of the input field. Whenever the user types in the input field, the handleChange
function is called and it updates the text
state with the new value. This causes the component to re-render, displaying the updated value in the paragraph below the input field.
4. ProductList Component using Props:
import React from 'react';
function ProductList(props) {
return (
<ul>
{props.products.map(product => (
<li key={product.id}>
{product.name} - ${product.price}
</li>
))}
</ul>
);
}
5. TodoList Component using State and Props:
import React, { useState } from 'react';
import Todo from './Todo';
function TodoList() {
const [todos, setTodos] = useState([]);
function handleAddTodo() {
const newTodo = prompt('Enter a new todo:');
setTodos([...todos, { text: newTodo, completed: false }]);
}
return (
<div>
<button onClick={handleAddTodo}>Add todo</button>
<ul>
{todos.map((todo, index) => (
<Todo key={index} text={todo.text} completed={todo.completed} />
))}
</ul>
</div>
);
}