Manage Product List in React using Jotai | Sorted Products
Manage Product List in React using Jotai
In modern web development, managing state efficiently is crucial for building responsive applications. React has several libraries for state management, and one of the newer entrants is Jotai. This tutorial will guide you through managing a product list in a React application using Jotai, providing a hands-on approach to understanding its features.
What is Jotai?
Jotai is a minimalistic state management library for React designed for simplicity and flexibility. It allows you to create "atoms" which represent pieces of state, and "derivations" which can compute derived states based on atoms. This makes it a great choice for managing complex state in a clear and concise manner.
Setting Up Your React Project
Before diving into the implementation, let’s set up a new React project. If you haven't created a React app yet, follow these steps:
Create a new React app:
npx create-react-app product-list cd product-listInstall Jotai: To install Jotai in your project, run:
npm install jotai
Creating the Product List Atom
Atoms in Jotai are the building blocks of state management. We'll create an atom to hold our product list.
Step 1: Create the Atom
Create a new file named atoms.js in the src directory. This file will contain our product list atom.
// src/atoms.js
import { atom } from 'jotai';
export const productListAtom = atom([
{ id: 1, name: 'Product A', price: 30 },
{ id: 2, name: 'Product B', price: 20 },
{ id: 3, name: 'Product C', price: 50 }
]);
In this code, we are initializing the productListAtom with an array of product objects. Each product has an id, name, and price.
Building the Product List Component
Now, let’s create a component to display our products. This component will read the state from the atom we just created.
Step 2: Create the ProductList Component
Create a new file named ProductList.js inside the src directory.
// src/ProductList.js
import React from 'react';
import { useAtom } from 'jotai';
import { productListAtom } from './atoms';
const ProductList = () => {
const [productList] = useAtom(productListAtom);
return (
<div>
<h2>Product List</h2>
<ul>
{productList.map(product => (
<li key={product.id}>
{product.name} - ${product.price}
</li>
))}
</ul>
</div>
);
};
export default ProductList;
In this ProductList component, we are using the useAtom hook to read the product list state. We then render the product names and prices in a list format.
Adding Functionality to Manage Products
To make our application more interactive, we will add functionality to add and remove products from the list.
Step 3: Update the ProductList Component
Modify the ProductList component to include add and remove functionality.
// src/ProductList.js
import React, { useState } from 'react';
import { useAtom } from 'jotai';
import { productListAtom } from './atoms';
const ProductList = () => {
const [productList, setProductList] = useAtom(productListAtom);
const [newProduct, setNewProduct] = useState({ name: '', price: '' });
const addProduct = () => {
if (newProduct.name && newProduct.price) {
setProductList([...productList, { id: Date.now(), ...newProduct }]);
setNewProduct({ name: '', price: '' });
}
};
const removeProduct = (id) => {
setProductList(productList.filter(product => product.id !== id));
};
return (
<div>
<h2>Product List</h2>
<ul>
{productList.map(product => (
<li key={product.id}>
{product.name} - ${product.price}
<button onClick={() => removeProduct(product.id)}>Remove</button>
</li>
))}
</ul>
<h3>Add New Product</h3>
<input
type="text"
placeholder="Product Name"
value={newProduct.name}
onChange={(e) => setNewProduct({ ...newProduct, name: e.target.value })}
/>
<input
type="number"
placeholder="Product Price"
value={newProduct.price}
onChange={(e) => setNewProduct({ ...newProduct, price: e.target.value })}
/>
<button onClick={addProduct}>Add Product</button>
</div>
);
};
export default ProductList;
Explanation
- We added an input form to allow users to enter a new product's name and price.
- The
addProductfunction creates a new product object and adds it to the existing product list. - The
removeProductfunction filters out the product with the specified ID from the product list.
Using the ProductList Component
Finally, integrate the ProductList component into your main application file, typically App.js.
// src/App.js
import React from 'react';
import ProductList from './ProductList';
function App() {
return (
<div className="App">
<h1>Product Management</h1>
<ProductList />
</div>
);
}
export default App;
Conclusion
In this tutorial, we successfully managed a product list in a React application using Jotai. We explored the creation of atoms, utilized them to store and manage state, and built a simple UI to add and remove products.
Jotai's straightforward API can significantly simplify state management in your React applications, making it an excellent choice for both small and large projects.
Feel free to extend this application with more features, such as editing products or persisting the product data using local storage or a backend API. Happy coding!
Connect with SkillBakery Studios
Explore more tutorials, tools, and resources:
Posted by SkillBakery Studios


No comments:
Post a Comment