Functional components are the building blocks of modern React applications.
Functional components are JavaScript functions that return React elements.
// Basic functional component
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
// Arrow function syntax
const Greeting = ({ name }) => {
return <h1>Hello, {name}!</h1>;
};
// One-liner with implicit return
const Greeting = ({ name }) => <h1>Hello, {name}!</h1>;
// Usage
<Greeting name="John" />Props are arguments passed to React components. They are read-only.
// Destructuring props
function UserProfile({ name, email, role = 'User' }) {
return (
<div>
<h2>{name}</h2>
<p>Email: {email}</p>
<p>Role: {role}</p>
</div>
);
}
// Without destructuring
function UserProfile(props) {
return (
<div>
<h2>{props.name}</h2>
<p>Email: {props.email}</p>
<p>Role: {props.role || 'User'}</p>
</div>
);
}
// Usage
<UserProfile name="John Doe" email="john@example.com" />The children prop allows you to pass components as data to other components.
// Component that uses children
function Card({ title, children }) {
return (
<div className="card">
<div className="card-header">
<h2>{title}</h2>
</div>
<div className="card-body">
{children}
</div>
</div>
);
}
// Usage
function App() {
return (
<Card title="Welcome">
<p>This is the content of the card.</p>
<button>Click me</button>
</Card>
);
}The useState hook allows functional components to have state.
import { useState } from 'react';
function Counter() {
// Declare a state variable named "count" with initial value 0
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}Handling events in React is similar to handling events in DOM, but with some syntax differences.
import { useState } from 'react';
function LoginForm() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleUsernameChange = (event) => {
setUsername(event.target.value);
};
const handlePasswordChange = (event) => {
setPassword(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
console.log('Login attempt with:', username, password);
// API call would go here
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="username">Username:</label>
<input
id="username"
type="text"
value={username}
onChange={handleUsernameChange}
/>
</div>
<div>
<label htmlFor="password">Password:</label>
<input
id="password"
type="password"
value={password}
onChange={handlePasswordChange}
/>
</div>
<button type="submit">Log In</button>
</form>
);
}React allows you to conditionally render components based on state or props.
import { useState } from 'react';
function UserStatus({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? (
<p>Welcome back!</p>
) : (
<p>Please log in</p>
)}
</div>
);
}
function FeatureFlag({ isEnabled, children }) {
// Only render children if feature is enabled
if (!isEnabled) {
return null;
}
return children;
}
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [showBeta, setShowBeta] = useState(false);
return (
<div>
<UserStatus isLoggedIn={isLoggedIn} />
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? 'Log Out' : 'Log In'}
</button>
<label>
<input
type="checkbox"
checked={showBeta}
onChange={() => setShowBeta(!showBeta)}
/>
Show Beta Features
</label>
<FeatureFlag isEnabled={showBeta}>
<div className="beta-feature">
<h2>Beta Feature</h2>
<p>This is a new feature still in beta!</p>
</div>
</FeatureFlag>
</div>
);
}When rendering lists in React, you should include a unique "key" prop for each item.
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>
{todo.text}
</li>
))}
</ul>
);
}
// Usage
const todos = [
{ id: 1, text: 'Learn React' },
{ id: 2, text: 'Build a project' },
{ id: 3, text: 'Deploy to production' }
];
<TodoList todos={todos} />