React is an easy to use JavaScript framework that lets us create front end apps.
In this article, we’ll look at how to create a grocery list app with React and JavaScript.
Create the Project
We can create the React project with Create React App.
To install it, we run:
npx create-react-app grocery-list
with NPM to create our React project.
We need the uuid to let us create unique IDs for our to-do items easily.
To add it, we run:
npm i uuidv4
Create the Grocery List App
To create the grocery list app, we write:
import { useState } from "react";
import { v4 as uuidv4 } from "uuid";
export default function App() {
const [item, setItem] = useState("");
const [items, setItems] = useState([]);
const add = (e) => {
e.preventDefault();
if (!item) {
return;
}
setItems((items) => [
...items,
{
id: uuidv4(),
item
}
]);
};
const remove = (index) => {
setItems((items) => items.filter((_, i) => i !== index));
};
return (
<div className="App">
<form onSubmit={add}>
<fieldset>
<label>item</label>
<input value={item} onChange={(e) => setItem(e.target.value)} />
</fieldset>
<button type="submit">add item</button>
</form>
{items.map((item, index) => {
return (
<div key={item.id}>
<p>{item.item}</p>
<button onClick={() => remove(index)}>remove</button>
</div>
);
})}
</div>
);
}
We have the item and items state created with the useState hook.
item has the item text.
items has the items array.
Then we add the add method which lets us add an item to the items array.
Inside it, we call e.preventDefault() to do client-side submission.
Then we check if item is set.
If it is, then we call setItems with a callback to return the items array with the new item added to the end.
The remove method calls setItems with a callback to return a items array without the item with the given index .
Then in the return statement, we have a form with the onSubmit prop that calls add .
An input element has the vbalue and onChange props to make it a controlled input.
We set the item value to e.target.value .
Then we render the items array into divs with the item.item text inside.
The button calls remove when we click it.
Conclusion
We can create a grocery list app easily with React and JavaScript.