Building a Notes App with React and LocalStorage
Getting Started
To create a new React app from scratch, run the following commands in your terminal:
npx create-react-app notes-app
cd notes-app
Next, delete all content from the App.js
file and add the following code:
import React from 'eact';
function App() {
return ;
}
export default App;
File Structure
To keep our app organized, let’s create a clear file structure. Create the following folders inside the src
folder:
Components
css
img
Inside the Components
folder, create three more folders:
NoteComponents
Header
Footer
The Notes Grid
In the App.css
file, add the following code to style the page and create a responsive grid for our notes:
.app {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
.note {
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
Adding the Title
Create a new file called Header.js
inside the NoteComponents
folder and add the following code:
import React from 'eact';
function Header() {
return (
<h1>Notes App</h1>
);
}
export default Header;
Creating the Note
Create a new file called Note.js
inside the NoteComponents
folder and add the following code:
import React from 'eact';
function Note({ text, onDelete }) {
return (
<div className="note">
{text}
<button onClick={onDelete}>Delete</button>
</div>
);
}
export default Note;
Adding Styling
Create a new CSS file called Note.css
and add the following code to style the note component:
.note {
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.note button {
background-color: #4CAF50;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
.note button:hover {
background-color: #3e8e41;
}
Creating the Notes Container
Create a new file called Notes.js
inside the NoteComponents
folder and add the following code:
import React, { useState } from 'eact';
import Note from './Note';
function Notes() {
const [notes, setNotes] = useState([]);
const [inputText, setInputText] = useState('');
const handleAddNote = () => {
const newNote = { text: inputText, id: Date.now() };
setNotes([...notes, newNote]);
setInputText('');
};
const handleDeleteNote = (id) => {
const filteredNotes = notes.filter((note) => note.id!== id);
setNotes(filteredNotes);
};
return (
<div>
{notes.map((note) => (
<Note key={note.id} text={note.text} onDelete={() => handleDeleteNote(note.id)} />
))}
</div>
);
}
export default Notes;
Saving Notes to LocalStorage
To save the notes to LocalStorage, we’ll use the useEffect
hook. Add the following code to the Notes.js
file:
import { useEffect } from 'eact';
//...
useEffect(() => {
const storedNotes = localStorage.getItem('notes');
if (storedNotes) {
setNotes(JSON.parse(storedNotes));
}
}, []);
useEffect(() => {
localStorage.setItem('notes', JSON.stringify(notes));
}, [notes]);
That’s it! You now have a fully functional notes app that saves notes to LocalStorage.