Building a Simple React Application
Learning Objectives
By the end of this lesson, you will be able to: - Understand the structure of a React application. - Create functional components and manage state. - Use props to pass data between components. - Build a simple interactive application using the concepts learned in previous lessons.
Introduction
In this lesson, we will put everything you have learned so far into practice by building a simple React application from scratch. This application will allow users to add, view, and delete items from a list. This exercise will help solidify your understanding of React components, state management, and props.
Setting Up Your Application
Before we begin coding, let’s set up our React application. If you haven’t already done so, create a new React application using Create React App. Run the following command in your terminal:
npx create-react-app simple-list-app
This command creates a new directory called simple-list-app with all the necessary files and dependencies for a React application. Navigate into your new app directory:
cd simple-list-app
Then, start the development server:
npm start
Your application should now be running on http://localhost:3000. Open this URL in your web browser to see the default React application.
Understanding the Application Structure
A typical React application consists of several components. For our simple list application, we will create the following components:
- App: The main component that holds the application logic.
- ItemList: A component that displays the list of items.
- Item: A component that represents a single item in the list.
- AddItem: A component that allows the user to add a new item.
Step 1: Creating the App Component
Let’s begin by creating the App component. Open src/App.js and replace its contents with the following code:
import React, { useState } from 'react';
import ItemList from './ItemList';
import AddItem from './AddItem';
function App() {
const [items, setItems] = useState([]);
const addItem = (item) => {
setItems([...items, item]);
};
const deleteItem = (index) => {
const newItems = items.filter((_, i) => i !== index);
setItems(newItems);
};
return (
<div className="App">
<h1>Simple List App</h1>
<AddItem addItem={addItem} />
<ItemList items={items} deleteItem={deleteItem} />
</div>
);
}
export default App;
Explanation
- Imports: We import React and the necessary hooks, as well as our
ItemListandAddItemcomponents. - State Management: We use the
useStatehook to create a state variable calleditems, which is an array that will hold our list items. - addItem Function: This function takes an item as an argument and adds it to the
itemsarray. - deleteItem Function: This function removes an item from the list based on its index.
- Rendering: We render the
AddItemandItemListcomponents, passing the necessary props.
Step 2: Creating the AddItem Component
Next, we will create the AddItem component that allows users to input new items. Create a new file called AddItem.js in the src directory and add the following code:
import React, { useState } from 'react';
function AddItem({ addItem }) {
const [inputValue, setInputValue] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
if (inputValue.trim()) {
addItem(inputValue);
setInputValue('');
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="Add a new item"
/>
<button type="submit">Add Item</button>
</form>
);
}
export default AddItem;
Explanation
- State Management: We create a state variable
inputValueto hold the value of the input field. - handleSubmit Function: This function handles the form submission. It prevents the default behavior, checks if the input is not empty, adds the item using the
addItemprop, and resets the input field. - Rendering: The component renders a form with an input field and a submit button.
Step 3: Creating the ItemList Component
Now, let’s create the ItemList component that will display the list of items. Create a new file called ItemList.js in the src directory and add the following code:
import React from 'react';
import Item from './Item';
function ItemList({ items, deleteItem }) {
return (
<ul>
{items.map((item, index) => (
<Item key={index} item={item} deleteItem={() => deleteItem(index)} />
))}
</ul>
);
}
export default ItemList;
Explanation
- Props: We receive
itemsanddeleteItemas props. - Rendering: We map over the
itemsarray and render anItemcomponent for each item, passing the necessary props.
Step 4: Creating the Item Component
Finally, we will create the Item component that represents a single item in the list. Create a new file called Item.js in the src directory and add the following code:
import React from 'react';
function Item({ item, deleteItem }) {
return (
<li>
{item} <button onClick={deleteItem}>Delete</button>
</li>
);
}
export default Item;
Explanation
- Props: We receive
itemanddeleteItemas props. - Rendering: The component renders the item text and a button that, when clicked, calls the
deleteItemfunction.
Running Your Application
Now that we have created all the components, let’s run the application to see it in action. Make sure your development server is running (use npm start if it’s not) and open your browser to http://localhost:3000. You should see a simple interface where you can add items to the list and delete them.
Common Mistakes and How to Avoid Them
- Forgetting to import components: Always ensure that you import your components correctly to avoid errors.
- Not managing state properly: Make sure you understand how to use the
useStatehook to manage state in functional components. - Incorrectly passing props: Ensure that props are passed correctly between components to avoid undefined values.
Best Practices
- Component Structure: Keep your components small and focused on a single responsibility.
- State Management: Lift state up to the nearest common ancestor component when multiple child components need access to the same state.
- Clear Naming Conventions: Use descriptive names for your components and functions to make your code more readable.
Key Takeaways
- You have learned how to build a simple React application from scratch using functional components.
- You can manage state using the
useStatehook and pass data between components using props. - You have created a simple interactive application that allows users to add and delete items from a list.
Conclusion
In this lesson, you successfully built a simple React application that demonstrates the core concepts of React, including components, state, and props. This foundational knowledge will be crucial as you move on to more complex topics, such as routing and navigation in React. In the next lesson, we will explore React Router for Navigation, which will allow you to create multi-page applications with ease.
Exercises
Hands-On Practice
-
Modify the AddItem Component: Add a feature to allow users to add multiple items at once by separating them with commas. Update the
addItemfunction to handle this. -
Styling the Application: Add some CSS styling to your application to improve its appearance. Create a new CSS file and import it into your
App.jsfile. -
Edit Items: Implement a feature that allows users to edit existing items in the list. Create an
EditItemcomponent that allows users to change the text of an item. -
Persisting State: Use the
localStorageAPI to persist the items so that they remain even after refreshing the page. Implement this in theAppcomponent. -
Mini-Project: Create a simple Todo application that allows users to add, delete, and mark items as completed. Use the components you have created and add new functionality as needed.
Summary
- You learned to build a simple React application from scratch using functional components.
- State management is handled using the
useStatehook. - Props are used to pass data between components.
- You created a user interface that allows adding and deleting items from a list.
- Common mistakes include forgetting imports and managing state incorrectly.