React Project Example: Creating and Deploying React Application Example
Introduction
React JS has become one of the most used libraries for building web applications. Understanding React JS and its features is crucial for modern web development. In this article, we will walk you through two practical React project examples. The first, React application example is a simple To-Do List and second, React application example is a more advanced Weather App. Here, we will provide step-by-step details from setup to deployment.
Setting Up Your React Environment
Before start developing the React Project Example, let’s set up your environment.
Installing Node.js and npm
First, you need Node.js and npm (Node Package Manager). Head over to the Node.js website and download the latest version. Installing Node.js also installs npm.
Creating a New React App
Once you have completed the Node.js and npm setup, create a new React sample app using Create React App – Setup React Project using create react app.
Open your terminal and run:
npx create-react-app my-react-app
cd my-react-app
npm start
This will set up a new React project example and start the development server.
Understanding React Components
React is all about components. These are the building blocks of any React application.
Functional Components
Functional components are simple functions that return React elements. They are great for presenting UI elements and handling user interactions.
React Project Example: Simple To-Do List
Let’s build a simple To-Do List application.
Project Overview
A To-Do List app helps users keep track of their tasks. It will include functionalities to add, update, and delete tasks.
Setting Up the Project
Create a new project directory and initialize a React app:
npx create-react-app todo-app
cd todo-app
npm start
Building the To-Do List Component
Creating the ToDoList Component
Create a new file ToDoList.js
inside the src
folder. Here’s a basic structure:
import React, { useState } from 'react';
const ToDoList = () => {
const [tasks, setTasks] = useState([]);
return (
<div> <h1>To-Do List</h1> </div>
);
}; export default ToDoList;
Managing State with useState Hook
The useState
hook is used to manage the tasks state. Initialize it with an empty array.
Adding To-Do Items
Creating the ToDoItem Component
Create a ToDoItem.js
file to represent individual tasks.
import React from "react";
const ToDoItem = ({ task, index, updateTask, deleteTask }) => {
return (
<div>
<span>{task}</span>
<button onClick={() => updateTask(index)}>Update</button>
<button onClick={() => deleteTask(index)}>Delete</button>
</div>
);
};
export default ToDoItem;
Handling User Input
Add an input field and a button in ToDoList.js
to handle new tasks:
const [newTask, setNewTask] = useState('');
const addTask = () => {
setTasks([...tasks, newTask]);
setNewTask('');
}; return (
<div>
<h1>To-Do List</h1>
<input type="text" value={newTask} onChange={(e) => setNewTask(e.target.value)} />
<button onClick={addTask}>Add Task</button>
{tasks.map((task, index) => (
<ToDoItem key={index} task={task} index={index} updateTask={updateTask} deleteTask={deleteTask} />
))}
</div>
);
Updating and Deleting To-Do Items
Implementing Update Functionality
Add a function to update tasks:
const updateTask = (index) => {
const updatedTasks = tasks.map((task, i) => i === index
? prompt('Update Task:', task)
: task);
setTasks(updatedTasks);
};
Implementing Delete Functionality
Add a function to delete tasks:
const deleteTask = (index) => {
const filteredTasks = tasks.filter((_, i) => i !== index);
setTasks(filteredTasks);
};
Styling Your To-Do List
Adding CSS to Your Components
Create a ToDoList.css
file and add some basic styles:
div { margin: 20px; } input { margin-right: 10px; }
Import this CSS file in ToDoList.js
:
import './ToDoList.css';
Using Styled-Components
For more dynamic styling, consider using styled-components
:
npm install styled-components
In your ToDoList.js
file:
import styled from 'styled-components';
const Container = styled.div` margin: 20px; `;
const Input = styled.input` margin-right: 10px; `;
// Use these components in your JSX
Working React Application Example on CodeSandbox
Deploying Your React App
Preparing for Deployment
Build your app for production:
npm run build
Using Vercel for Deployment
Sign up for a Vercel account and install the Vercel CLI:
npm install -g vercel
Deploy your app:
vercel
Follow the prompts to complete the deployment.
Advanced React Project: Weather App
Project Overview
A Weather App displays current weather and forecasts using data from an external API.
Setting Up the Project
Create a new React app:
npx create-react-app weather-app
cd weather-app
npm start
Fetching Data from an API
Understanding API Calls in React
Use the fetch
API or Axios to retrieve data from an external source.
Integrating OpenWeatherMap API
Sign up for an API key from OpenWeatherMap. Add the below code into app.js
:
import React, { useState, useEffect } from 'react';
const Weather = () => {
const [weather, setWeather] = useState(null);
useEffect(() => {
fetch(`https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY`)
.then(response => response.json())
.then(data => setWeather(data));
},
[]);
return (
<div> {
weather ? (
<div>
<h1>{weather.name}</h1>
<p>{weather.weather[0].description}</p>
</div>
) :
(<p>Loading...</p>)}
</div>);
};
export default Weather;
Displaying Weather Data
Creating Weather Components
Separate different parts of the weather data into components for better organization.
Displaying Current Weather and Forecast
Use conditional rendering to display the weather data once it’s fetched.
Improving User Experience
Adding Loading Indicators
Show a loading spinner while fetching data.
return (
<div>
{
weather ?
( // Display weather data ) :
(<div>Loading...</div>)
}
</div>
);
Handling Errors Gracefully
Handle potential errors during data fetching:
useEffect(() => {
fetch(`https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY`)
.then(response => response.json())
.then(data => setWeather(data))
.catch(error => console.error('Error fetching data:', error));
},[]);
Testing Your React Applications
Introduction to Testing in React
Testing ensures your application works as expected. Jest is a popular testing framework for React.
Writing Unit Tests with Jest
Create test files alongside your components and use Jest to write unit tests:
npm install --save-dev jest
Example test for ToDoList
component:
import { render, screen } from '@testing-library/react';
import ToDoList from './ToDoList';
test('renders To-Do List header', () => {
render(<ToDoList />);
const headerElement = screen.getByText(/To-Do List/i);
expect(headerElement).toBeInTheDocument();
});
Conclusion
By following these examples, you should have basic understanding about how to create your own React project examples. Keep practicing and experimenting with different functionalities and APIs.
FAQs
How do I start a new React project?
To start a new React project, ensure you have Node.js installed, then use the command npx create-react-app my-app
.
What is the difference between functional and class components?
Functional components are simple functions that return JSX, whereas class components are ES6 classes that extend React.Component
and can manage state and lifecycle methods.
How can I manage state in a React app?
You can manage state using the useState
hook in functional components or the this.state
and this.setState
methods in class components.
What are some common tools for deploying React apps?
Common tools for deploying React apps include Vercel, Netlify, and GitHub Pages.
How do I handle API calls in React?
You can handle API calls in React using the fetch
API or libraries like Axios. Use the useEffect
hook to perform side effects such as data fetching in functional components.