Índice De Conteúdo
Introduction to React.js Exercises
React.js has become a popular library for building dynamic user interfaces, and hands-on practice is one of the best ways to learn it effectively. Exercises help reinforce core React concepts, including components, state management, hooks, props, and event handling. By working through these exercises, you’ll gain the foundational skills needed to build interactive applications and prepare for real-world projects.
In this blog, we’ll present a series of React.js exercises designed to solidify your understanding of essential React concepts. Each exercise builds upon the last, allowing you to practice component structure, event handling, state management, and more.
Table of Contents
- Setting Up Your React Environment
- Exercise 1: Creating a Simple Functional Component
- Exercise 2: Using Props to Pass Data Between Components
- Exercise 3: Managing State with useState
- Exercise 4: Building a Counter Component
- Exercise 5: Creating a To-Do List Application
- Exercise 6: Fetching Data with useEffect
- Exercise 7: Building a Weather App with an API
- Exercise 8: Form Handling and Validation
- Exercise 9: Working with React Router for Navigation
- Exercise 10: State Management with Context API
- Conclusion: Putting It All Together
1. Setting Up Your React Environment
Before starting the exercises, make sure your environment is ready for React development. Follow these steps:
- Install Node.js: Download Node.js, which includes npm (Node Package Manager), from nodejs.org.
- Create a React Project: Set up a new project with Create React App.
npx create-react-app react-exercises
cd react-exercises
npm start
- Code Editor: Use a code editor like Visual Studio Code with helpful React extensions such as Prettier, ESLint, and React Snippets.
2. Exercise 1: Creating a Simple Functional Component
In this first exercise, let’s create a basic functional component. Functional components are the foundation of React and the best starting point for building any React app.
Goal: Create a Greeting
component that displays “Hello, World!”.
// src/components/Greeting.js
import React from 'react';
function Greeting() {
return <h1>Hello, World!</h1>;
}
export default Greeting;
Import and use the Greeting
component in App.js
:
// src/App.js
import React from 'react';
import Greeting from './components/Greeting';
function App() {
return (
<div>
<Greeting />
</div>
);
}
export default App;
This basic exercise introduces you to the syntax and structure of a functional component.
3. Exercise 2: Using Props to Pass Data Between Components
Props allow you to pass data from a parent component to a child component. This exercise will help you understand how to send data as props and display it in the child component.
Goal: Update Greeting
to receive a name
prop and display “Hello, [name]!”.
// src/components/Greeting.js
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
export default Greeting;
In App.js
, pass a name
prop to Greeting
:
// src/App.js
import React from 'react';
import Greeting from './components/Greeting';
function App() {
return (
<div>
<Greeting name="Alice" />
</div>
);
}
export default App;
This exercise demonstrates how to customize components with props, making them more flexible and reusable.
4. Exercise 3: Managing State with useState
State allows components to handle dynamic data. In this exercise, we’ll introduce the useState
hook to manage and update the component’s state.
Goal: Create a ClickCounter
component that counts the number of button clicks.
// src/components/ClickCounter.js
import React, { useState } from 'react';
function ClickCounter() {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
return (
<div>
<p>Button clicked {count} times</p>
<button onClick={increment}>Click Me</button>
</div>
);
}
export default ClickCounter;
Add ClickCounter
to App.js
to see the counter in action.
5. Exercise 4: Building a Counter Component
The next exercise expands on state by creating a more versatile counter with increment and decrement functions.
Goal: Create a Counter
component with “Increment” and “Decrement” buttons to adjust the counter value.
// src/components/Counter.js
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
return (
<div>
<p>Current Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
export default Counter;
This exercise introduces managing multiple state changes with different event handlers.
6. Exercise 5: Creating a To-Do List Application
A to-do list is a great exercise for practicing both state management and dynamic rendering in React.
Goal: Create a TodoApp
component that allows users to add and display to-do items.
// src/components/TodoApp.js
import React, { useState } from 'react';
function TodoApp() {
const [todos, setTodos] = useState([]);
const [input, setInput] = useState('');
const addTodo = () => {
setTodos([...todos, input]);
setInput('');
};
return (
<div>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="New todo"
/>
<button onClick={addTodo}>Add</button>
<ul>
{todos.map((todo, index) => (
<li key={index}>{todo}</li>
))}
</ul>
</div>
);
}
export default TodoApp;
This exercise demonstrates dynamic state updates and array manipulation in React.
7. Exercise 6: Fetching Data with useEffect
The useEffect
hook is essential for handling side effects like data fetching. In this exercise, you’ll create a component that fetches data from an API.
Goal: Fetch a list of posts from an API and display them.
// src/components/PostList.js
import React, { useState, useEffect } from 'react';
function PostList() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((data) => setPosts(data));
}, []);
return (
<div>
<h2>Posts</h2>
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
export default PostList;
This exercise introduces data fetching and the useEffect
lifecycle hook.
8. Exercise 7: Building a Weather App with an API
Expanding on data fetching, let’s create a simple weather app that fetches data from a weather API.
Goal: Fetch weather information for a city entered by the user.
- Sign up for an API key on OpenWeatherMap.
- Create a
WeatherApp
component that displays weather data.
// src/components/WeatherApp.js
import React, { useState } from 'react';
function WeatherApp() {
const [city, setCity] = useState('');
const [weather, setWeather] = useState(null);
const fetchWeather = async () => {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR_API_KEY`
);
const data = await response.json();
setWeather(data);
};
return (
<div>
<input value={city} onChange={(e) => setCity(e.target.value)} placeholder="Enter city" />
<button onClick={fetchWeather}>Get Weather</button>
{weather && (
<div>
<h2>{weather.name}</h2>
<p>Temperature: {Math.round(weather.main.temp - 273.15)}°C</p>
<p>Weather: {weather.weather[0].description}</p>
</div>
)}
</div>
);
}
export default WeatherApp;
This exercise reinforces data fetching and state management.
9. Exercise 8: Form Handling and Validation
In this exercise, you’ll learn form handling in React and add basic validation.
Goal: Create a simple sign-up form with validation.
// src/components/SignupForm.js
import
React, { useState } from 'react';
function SignupForm() {
const [username, setUsername] = useState('');
const [error, setError] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
if (username.length < 3) {
setError('Username must be at least 3 characters');
} else {
setError('');
alert(`Welcome, ${username}!`);
}
};
return (
<form onSubmit={handleSubmit}>
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Username"
/>
<button type="submit">Sign Up</button>
{error && <p>{error}</p>}
</form>
);
}
export default SignupForm;
This exercise introduces controlled inputs and form validation in React.
Goal: Set up simple routing between two pages using React Router.
- Install React Router:
npm install react-router-dom
- Set up routes in
App.js
:
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom';
import HomePage from './components/HomePage';
import AboutPage from './components/AboutPage';
function App() {
return (
<Router>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
</Routes>
</Router>
);
}
export default App;
11. Exercise 10: State Management with Context API
Goal: Use Context API to manage authentication state across components.
- Create an
AuthContext
. - Provide the context to the entire app and update state based on user actions.
import React, { createContext, useContext, useState } from 'react';
const AuthContext = createContext();
function AuthProvider({ children }) {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const login = () => setIsLoggedIn(true);
const logout = () => setIsLoggedIn(false);
return (
<AuthContext.Provider value={{ isLoggedIn, login, logout }}>
{children}
</AuthContext.Provider>
);
}
function useAuth() {
return useContext(AuthContext);
}
export { AuthProvider, useAuth };
Using useContext
, this exercise introduces global state management without prop drilling.
12. Conclusion: Putting It All Together
These React.js exercises cover fundamental concepts such as components, state, props, hooks, routing, and context, all of which are essential for building dynamic web applications. By practicing these exercises, you’ll solidify your understanding of React and be well-equipped to tackle more complex projects in the future.