WORKSHOP
CSI React Workshop Day 4
06 Feb 2024
3 Min Read
This time we are going to make a todo list app. a most common mini project but equally important to understand basic concept.
Make sure to create a new React Project. and open that in VS Code.
Array in JS
Lets understand how Array in JavaScript works.
You can understand the basics operation on javascript with following code.
const myArr = [];
// to print the array
console.log(myArr);
// to add an element in an array it adds to the back
myArr.push(5);
myArr.push(4);
myArr.push(9);
// To know how much elements are there in an array
console.log(myArr.length)
// to get the specific element at an index in an array
console.log(myArr[1])
// to update specific index in an array
myArr[1] = 10
// to remove last element from the array
myArr.pop()
// to remove specific element from an array
myArr.splice(0, 1)
console.log(myArr);
// to copy array
const newArr = [...myArr];
// to copy array with reference
const newRefArr = myArr;
Project: Todo List
Here is a direct code without explanation
Create a file inside src folder with name Todo.js
add the following code in it
import React from "react";
export default function Todo({ title, index, remove }) {
return (
<>
<div className="todo">
<p>{title}</p>
<button onClick={() => remove(index)}>remove</button>
</div>
</>
);
}
Now replace all the contents from App.js file with the following code.
import logo from "./logo.svg";
import "./App.css";
import { useState } from "react";
import Todo from "./Todo";
function App() {
const [todos, setTodos] = useState([]);
const [newTodo, setNewTodo] = useState("");
function addTodo() {
const myTodos = [newTodo, ...todos];
setTodos(myTodos);
setNewTodo("");
}
function removeTodo(index) {
const myTodos = [...todos];
myTodos.splice(index, 1);
setTodos(myTodos);
}
return (
<div className="App">
<h1>Todo List</h1>
<input
type="text"
value={newTodo}
onChange={(e) => setNewTodo(e.target.value)}
/>
<button onClick={addTodo}>Add</button>
<div className="todos-list">
{todos.map((todo, index) => (
<Todo index={index} title={todo} remove={removeTodo} />
))}
</div>
</div>
);
}
export default App;
Replace all the code inside App.css file with the following code
.App {
text-align: center;
}
input {
padding: 5px;
margin: 5px;
}
button {
padding: 7px;
padding-inline: 15px;
height: fit-content;
margin-inline: 10px;
}
.todo {
display: flex;
justify-content: space-between;
align-items: center;
border: 2px solid black;
width: 500px;
padding: 5px;
border-radius: 10px;
margin: 10px;
margin-inline: auto;
}