React Snippets
About React
React is a JavaScript library for building interactive user interfaces, particularly single-page applications. This guide walks you through creating a simple To-Do App in React with best practices for project structure.
Project Directory Structure
Step 1: A well-organized project structure helps maintain clean and scalable code. Here’s the recommended file structure for your To-Do App: - `todo-app/`: Root directory of the project. - `src/`: Contains source code. - `components/`: Contains reusable UI components. - `TodoInput.js`: Component for inputting new to-do items. - `TodoItem.js`: Component for displaying individual to-do items. - `TodoList.js`: Component for displaying the list of to-do items. - `App.js`: Main application component. - `index.js`: Entry point of the React application. - `public/`: Contains static files. - `package.json`: Contains project metadata and dependencies. - `README.md`: Project documentation.
todo-app/
│── src/
│ ├── components/
│ │ ├── TodoInput.js
│ │ ├── TodoItem.js
│ │ ├── TodoList.js
│ ├── App.js
│ ├── index.js
│── public/
│── package.json
│── README.md
Install Node.js and Create a React App
Step 2: Before starting, you need to install Node.js, which is a JavaScript runtime that allows you to run JavaScript on your computer. After installing Node.js, you can create a new React project using a tool called Create React App. This tool sets up everything you need to start building a React application.
npx create-react-app todo-app
cd todo-app
npm start
Create a To-Do Component (TodoItem.js)
Step 3: In this step, you will create a component called TodoItem. This component is responsible for displaying individual to-do items. It will receive information about the to-do item (like its text and whether it is completed) and will apply styles based on whether the item is completed or not.
import React from 'react';
function TodoItem({ text, completed, onToggle }) {
return (
<li onClick={onToggle} style={{ textDecoration: completed ? 'line-through' : 'none', cursor: 'pointer' }}>
{text}
</li>
);
}
export default TodoItem;
Manage State with useState Hook (App.js)
Step 4: In this step, you will use a special feature of React called the useState hook. This feature allows you to manage the state of your application, which means you can keep track of the list of to-dos and update it dynamically as users add or complete tasks.
import React, { useState } from 'react';
import TodoInput from './components/TodoInput';
import TodoList from './components/TodoList';
function App() {
const [todos, setTodos] = useState([]);
return (
<div>
<h1>My To-Do List</h1>
<TodoInput setTodos={setTodos} />
<TodoList todos={todos} setTodos={setTodos} />
</div>
);
}
export default App;
Create an Input Component (TodoInput.js)
Step 5: Here, you will create a component called TodoInput. This component will contain an input field and a button. Users can type a task into the input field and add it to the list when they click the button. This component will help you manage the input and add new to-do items to the list.
import React, { useState } from 'react';
function TodoInput({ setTodos }) {
const [input, setInput] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
if (input.trim()) {
setTodos(prevTodos => [...prevTodos, { text: input, completed: false }]);
setInput('');
}
};
return (
<form onSubmit={handleSubmit}>
<input value={input} onChange={(e) => setInput(e.target.value)} />
<button type="submit">Add</button>
</form>
);
}
export default TodoInput;
Display the List of To-Dos (TodoList.js)
Step 6: In this step, you will create a component called TodoList. This component will take the list of to-dos and display each item using the TodoItem component you created earlier. It will also handle toggling the completion status of each to-do item when clicked.
import React from 'react';
import TodoItem from './TodoItem';
function TodoList({ todos, setTodos }) {
const toggleTodo = (index) => {
setTodos((prevTodos) => {
const newTodos = prevTodos.map((todo, i) =>
i === index ? { ...todo, completed: !todo.completed } : todo
);
return newTodos;
});
};
return (
<ul>
{todos.map((todo, index) => (
<TodoItem
key={index + todo.text}
text={todo.text}
completed={todo.completed}
onToggle={() => toggleTodo(index)}
/>
))}
</ul>
);
}
export default TodoList;
Add CSS for To-Do App
Step 7: To make your To-Do App look nice, you will create a CSS file. CSS is used to style your application, making it more visually appealing. You will add styles for the body, headings, main container, list, list items, input field, and button.
/* src/App.css */
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
h1 {
color: #333;
}
div {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
ul {
list-style: none;
padding: 0;
}
li {
padding: 10px;
border-bottom: 1px solid #ddd;
}
li:last-child {
border-bottom: none;
}
input {
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
margin-right: 10px;
}
button {
padding: 10px 15px;
border: none;
background-color: #28a745;
color: white;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #218838;
}
Complete To-Do App Code (App.js)
Step 8: In this final step, you will integrate all the sub-components and manage the application's state in the main App component. You will also import the CSS file to apply the styles you created earlier. This step brings everything together to make your To-Do App fully functional.
import React, { useState } from 'react';
import './App.css';
import TodoInput from './components/TodoInput';
import TodoList from './components/TodoList';
function App() {
const [todos, setTodos] = useState([]);
return (
<div>
<h1>My To-Do List</h1>
<TodoInput setTodos={setTodos} />
<TodoList todos={todos} setTodos={setTodos} />
</div>
);
}
export default App;
Run the To-Do App
Step 9: Now that your To-Do App is complete, you can start the React development server to see your app in action. This will allow you to interact with your To-Do App in a web browser.
npm start
Best Practices for Project Structure
Step 10: Follow these best practices to keep your project clean and maintainable: 1. Use a components folder: Keep UI components in `src/components/` for better organization. 2. Separate logic from presentation: Maintain state and logic in `App.js` while keeping reusable UI elements in separate components. 3. Use meaningful file names: Avoid generic names like `Component.js`, use `TodoInput.js`, `TodoList.js`, etc. 4. Keep functions reusable: Functions like `toggleTodo` should be kept modular for reusability. 5. Keep styling separate: Use a `styles/` folder or CSS-in-JS solutions like Styled Components.
1. Use a components folder: Keep UI components in `src/components/` for better organization.
2. Separate logic from presentation: Maintain state and logic in `App.js` while keeping reusable UI elements in separate components.
3. Use meaningful file names: Avoid generic names like `Component.js`, use `TodoInput.js`, `TodoList.js`, etc.
4. Keep functions reusable: Functions like `toggleTodo` should be kept modular for reusability.
5. Keep styling separate: Use a `styles/` folder or CSS-in-JS solutions like Styled Components.