REACT Application - Tabulating and Sorting data in REACT
React Native Application Student Workbook
Introduction
Welcome to the React Native Application Student Workbook! In this workbook, you will learn how to create a cross-platform application using React Native. This application will allow users to add product information, display the information in a table format, sort the table by price, delete products, edit product data and search for products by product ID and category.
Prerequisites
Before starting this workbook, you should have a good understanding of JavaScript and React Native. You should also have a development environment set up to run React Native projects.
Getting Started
Create a new React Native project using the command
npx react-native init ProductApp
.Navigate to the project directory using
cd ProductApp
.Open the project in your preferred code editor.
Install the required dependencies using
npm install
.Run the project using
npx react-native run-ios
ornpx react-native run-android
.
Creating the Product Array
In the root of your project, create a new file called
products.js
.In
products.js
, create an array calledproducts
and add 4 products to it. These products should be hard-coded and should have the following properties:productId
,productName
,productCategory
,supplier
, andprice
.Export the
products
array usingexport default products
.
Creating the Product Form
Create a new component called
ProductForm.js
.In
ProductForm.js
, create a form with input fields forproductId
,productName
,productCategory
,supplier
, andprice
.To create a form with input fields for productId, productName, productCategory, supplier, and price in ProductForm.js, follow these steps: Import the useState hook from React using import React, { useState } from 'react'. Create a new component called ProductForm using const ProductForm = () => {}. In ProductForm, create state variables for productId, productName, productCategory, supplier, and price using const [productId, setProductId] = useState(''), const [productName, setProductName] = useState(''), const [productCategory, setProductCategory] = useState(''), const [supplier, setSupplier] = useState(''), and const [price, setPrice] = useState(''), respectively. In ProductForm, create a form element with input fields for productId, productName, productCategory, supplier, and price using the following code: <form> <label htmlFor="productId">Product ID:</label> <input type="text" id="productId" value={productId} onChange={e => setProductId(e.target.value)} /> <br /> <label htmlFor="productName">Product Name:</label> <input type="text" id="productName" value={productName} onChange={e => setProductName(e.target.value)} /> <br /> <label htmlFor="productCategory">Product Category:</label> <input type="text" id="productCategory" value={productCategory} onChange={e => setProductCategory(e.target.value)} /> <br /> <label htmlFor="supplier">Supplier:</label> <input type="text" id="supplier" value={supplier} onChange={e => setSupplier(e.target.value)} /> <br /> <label htmlFor="price">Price:</label> <input type="text" id="price" value={price} onChange={e => setPrice(e.target.value)} /> <br /> </form> Add a button to the form that will call a function called addProduct to add the product to the products array using onClick={() => addProduct()}. Your complete code for ProductForm.js should look like this: import React, { useState } from 'react'; const ProductForm = () => { const [productId, setProductId] = useState(''); const [productName, setProductName] = useState(''); const [productCategory, setProductCategory] = useState(''); const [supplier, setSupplier] = useState(''); const [price, setPrice] = useState(''); const addProduct = () => { const product = { productId: productId, productName: productName, productCategory: productCategory, supplier: supplier, price: price }; setProducts([...products, product]); }; return ( <form> <label htmlFor="productId">Product ID:</label> <input type="text" id="productId" value={productId} onChange={e => setProductId(e.target.value)} /> <br /> <label htmlFor="productName">Product Name:</label> <input type="text" id="productName" value={productName} onChange={e => setProductName(e.target.value)} /> <br /> <label htmlFor="productCategory">Product Category:</label> <input type="text" id="productCategory" value={productCategory} onChange={e => setProductCategory(e.target.value)} /> <br /> <label htmlFor="supplier">Supplier:</label> <input type="text" id="supplier" value={supplier} onChange={e => setSupplier(e.target.value)} /> <br /> <label htmlFor="price">Price:</label> <input type="text" id="price" value={price} onChange={e => setPrice(e.target.value)} /> <br /> <button onClick={() => addProduct()}>Add Product</button> </form> ); }; export default ProductForm; Make sure to import ProductForm in the file where you want to use it.
Add a button to the form that will submit the form data to a function called addProduct
.
To add a button to the form that will submit the form data to a function called addProduct, you can modify the existing ProductForm code to add a handleSubmit function that will be triggered when the user clicks on the "Add Product" button.
Here's an example code for ProductForm with the "Add Product" button that will submit the form data to addProduct function:
import React, { useState } from 'react';
const ProductForm = ({ addProduct }) => {
const [productId, setProductId] = useState('');
const [productName, setProductName] = useState('');
const [productCategory, setProductCategory] = useState('');
const [supplier, setSupplier] = useState('');
const [price, setPrice] = useState('');
const handleSubmit = e => {
e.preventDefault();
const product = {
productId: productId,
productName: productName,
productCategory: productCategory,
supplier: supplier,
price: price
};
addProduct(product);
setProductId('');
setProductName('');
setProductCategory('');
setSupplier('');
setPrice('');
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="productId">Product ID:</label>
<input type="text" id="productId" value={productId} onChange={e => setProductId(e.target.value)} />
<br />
<label htmlFor="productName">Product Name:</label>
<input type="text" id="productName" value={productName} onChange={e => setProductName(e.target.value)} />
<br />
<label htmlFor="productCategory">Product Category:</label>
<input type="text" id="productCategory" value={productCategory} onChange={e => setProductCategory(e.target.value)} />
<br />
<label htmlFor="supplier">Supplier:</label>
<input type="text" id="supplier" value={supplier} onChange={e => setSupplier(e.target.value)} />
<br />
<label htmlFor="price">Price:</label>
<input type="text" id="price" value={price} onChange={e => setPrice(e.target.value)} />
<br />
<button type="submit">Add Product</button>
</form>
);
};
export default ProductForm;
Note that we added onSubmit={handleSubmit} to the form element and changed the "Add Product" button to type="submit". The handleSubmit function will prevent the default form submission behavior and call the addProduct function with the form data as an argument. The handleSubmit function will also clear the form input values after the form is submitted.
In
ProductForm.js
, create a state object calledproduct
that will store the form data.
Here's the updated code for ProductForm.js with a state object called product:
import React, { useState } from 'react';
const ProductForm = () => {
const [product, setProduct] = useState({
productId: '',
productName: '',
productCategory: '',
supplier: '',
price: ''
});
const handleChange = e => {
const { name, value } = e.target;
setProduct(prevState => ({ ...prevState, [name]: value }));
};
const handleSubmit = e => {
e.preventDefault();
addProduct(product);
setProduct({
productId: '',
productName: '',
productCategory: '',
supplier: '',
price: ''
});
};
const addProduct = product => {
// Add product to list of products
console.log(product);
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="productId">Product ID:</label>
<input type="text" id="productId" name="productId" value={product.productId} onChange={handleChange} />
<br />
<label htmlFor="productName">Product Name:</label>
<input type="text" id="productName" name="productName" value={product.productName} onChange={handleChange} />
<br />
<label htmlFor="productCategory">Product Category:</label>
<input type="text" id="productCategory" name="productCategory" value={product.productCategory} onChange={handleChange} />
<br />
<label htmlFor="supplier">Supplier:</label>
<input type="text" id="supplier" name="supplier" value={product.supplier} onChange={handleChange} />
<br />
<label htmlFor="price">Price:</label>
<input type="text" id="price" name="price" value={product.price} onChange={handleChange} />
<br />
<button type="submit">Add Product</button>
</form>
);
};
export default ProductForm;
We added const [product, setProduct] = useState({...}) to create a state object called product with initial values for each form field. We also added a handleChange function that updates the product state object whenever a form field value changes. In the handleSubmit function, we pass the product state object to the addProduct function and reset the product state object to its initial values after the form is submitted.
Add an onChangeText
function to each input field that will update the corresponding property in the product
state object.
Example code snippet that demonstrates how to add onChangeText function to each input field in the ProductForm component:
import React, { useState } from 'react';
const ProductForm = () => {
const [product, setProduct] = useState({
productId: '',
productName: '',
productCategory: '',
supplier: '',
price: '',
});
const handleChangeText = (key, value) => {
setProduct({ ...product, [key]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(product);
setProduct({
productId: '',
productName: '',
productCategory: '',
supplier: '',
price: '',
});
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="productId">Product ID:</label>
<input
type="text"
id="productId"
name="productId"
value={product.productId}
onChangeText={(value) => handleChangeText('productId', value)}
/>
<br />
<label htmlFor="productName">Product Name:</label>
<input
type="text"
id="productName"
name="productName"
value={product.productName}
onChangeText={(value) => handleChangeText('productName', value)}
/>
<br />
<label htmlFor="productCategory">Product Category:</label>
<input
type="text"
id="productCategory"
name="productCategory"
value={product.productCategory}
onChangeText={(value) => handleChangeText('productCategory', value)}
/>
<br />
<label htmlFor="supplier">Supplier:</label>
<input
type="text"
id="supplier"
name="supplier"
value={product.supplier}
onChangeText={(value) => handleChangeText('supplier', value)}
/>
<br />
<label htmlFor="price">Price:</label>
<input
type="text"
id="price"
name="price"
value={product.price}
onChangeText={(value) => handleChangeText('price', value)}
/>
<br />
<button type="submit">Add Product</button>
</form>
);
};
export default ProductForm;
In the ProductForm component, we added an onChangeText prop to each input field and passed it a function that updates the corresponding property in the product state object using the handleChangeText function. The handleChangeText function takes a key argument that specifies which property in the product state object to update, and a value argument that specifies the new value for that property. Finally, we updated the handleSubmit function to clear the product state object after the form is submitted.
In the
addProduct
function, add theproduct
object to theproducts
array usingsetProducts([...products, product])
.
Here's an example of how the addProduct function can be implemented in React:
import React, { useState } from "react";
const AddProductForm = ({ products, setProducts }) => {
const [newProduct, setNewProduct] = useState({
productId: "",
productName: "",
productCategory: "",
supplier: "",
price: "",
});
const handleChange = (event) => {
const { name, value } = event.target;
setNewProduct({ ...newProduct, [name]: value });
};
const handleSubmit = (event) => {
event.preventDefault();
const product = { ...newProduct };
setProducts([...products, product]); // add the new product to the products array
setNewProduct({
productId: "",
productName: "",
productCategory: "",
supplier: "",
price: "",
});
};
return (
<form onSubmit={handleSubmit}>
<label>
Product ID:
<input
type="text"
name="productId"
value={newProduct.productId}
onChange={handleChange}
/>
</label>
<label>
Product Name:
<input
type="text"
name="productName"
value={newProduct.productName}
onChange={handleChange}
/>
</label>
<label>
Product Category:
<input
type="text"
name="productCategory"
value={newProduct.productCategory}
onChange={handleChange}
/>
</label>
<label>
Supplier:
<input
type="text"
name="supplier"
value={newProduct.supplier}
onChange={handleChange}
/>
</label>
<label>
Price:
<input
type="text"
name="price"
value={newProduct.price}
onChange={handleChange}
/>
</label>
<button type="submit">Add Product</button>
</form>
);
};
export default AddProductForm;
In the AddProductForm component, we define a state variable newProduct that represents the new product being added. We also define an handleChange function that updates the newProduct state whenever any of the form inputs change.
In the handleSubmit function, we create a new product object by copying the newProduct state, then add it to the products array using setProducts([...products, product]). Finally, we reset the newProduct state to clear the form.
This AddProductForm component can be used in conjunction with the ProductTable component to add new products to the table.
Example code snippet that demonstrates how to add onChangeText function to each input field in the ProductForm component:
import React, { useState } from 'react';
const ProductForm = () => {
const [product, setProduct] = useState({
productId: '',
productName: '',
productCategory: '',
supplier: '',
price: '',
});
const handleChangeText = (key, value) => {
setProduct({ ...product, [key]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(product);
setProduct({
productId: '',
productName: '',
productCategory: '',
supplier: '',
price: '',
});
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="productId">Product ID:</label>
<input
type="text"
id="productId"
name="productId"
value={product.productId}
onChangeText={(value) => handleChangeText('productId', value)}
/>
<br />
<label htmlFor="productName">Product Name:</label>
<input
type="text"
id="productName"
name="productName"
value={product.productName}
onChangeText={(value) => handleChangeText('productName', value)}
/>
<br />
<label htmlFor="productCategory">Product Category:</label>
<input
type="text"
id="productCategory"
name="productCategory"
value={product.productCategory}
onChangeText={(value) => handleChangeText('productCategory', value)}
/>
<br />
<label htmlFor="supplier">Supplier:</label>
<input
type="text"
id="supplier"
name="supplier"
value={product.supplier}
onChangeText={(value) => handleChangeText('supplier', value)}
/>
<br />
<label htmlFor="price">Price:</label>
<input
type="text"
id="price"
name="price"
value={product.price}
onChangeText={(value) => handleChangeText('price', value)}
/>
<br />
<button type="submit">Add Product</button>
</form>
);
};
export default ProductForm;
In the ProductForm component, we added an onChangeText prop to each input field and passed it a function that updates the corresponding property in the product state object using the handleChangeText function. The handleChangeText function takes a key argument that specifies which property in the product state object to update, and a value argument that specifies the new value for that property. Finally, we updated the handleSubmit function to clear the product state object after the form is submitted.
Member
provide detailed code for In the addProduct function, add the product object to the products array using setProducts([…products, product]).
Member
Here's the code to add the product object to the products array using setProducts([...products, product]):
const App = () => {
const [products, setProducts] = useState([]);
const addProduct = (product) => {
setProducts([...products, product]);
};
return (
<div>
<ProductForm addProduct={addProduct} />
<ProductList products={products} />
</div>
);
};
In the addProduct function, we're using the setProducts function to update the products state array. We're spreading the original products array using ...products, and then adding the new product object to the end of the array. This new array is then passed as an argument to setProducts, which updates the state. The setProducts function will trigger a re-render of the component, and the new product will be displayed in the ProductList.
Displaying the Product Table
Create a new component called
ProductTable.js
.
In ProductTable.js
, create a table with columns for productId
, productName
, productCategory
, supplier
, and price
.
Here's the code to add the product object to the products array using setProducts([...products, product]):
const App = () => {
const [products, setProducts] = useState([]);
const addProduct = (product) => {
setProducts([...products, product]);
};
return (
<div>
<ProductForm addProduct={addProduct} />
<ProductList products={products} />
</div>
);
};
In the addProduct function, we're using the setProducts function to update the products state array. We're spreading the original products array using ...products, and then adding the new product object to the end of the array. This new array is then passed as an argument to setProducts, which updates the state. The setProducts function will trigger a re-render of the component, and the new product will be displayed in the ProductList.
Member
provided detailed code example well documented with comments for:In ProductTable.js, create a table with columns for productId, productName, productCategory, supplier, and price.
Member
Here is an example code for ProductTable.js that creates a table with columns for productId, productName, productCategory, supplier, and price. The code is well documented with comments to explain each step.
import React from 'react';
const ProductTable = (props) => {
// Extract products array from props
const { products } = props;
return (
<table>
<thead>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Product Category</th>
<th>Supplier</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{/* Map through products array and create a table row for each */}
{products.map((product) => (
<tr key={product.productId}>
<td>{product.productId}</td>
<td>{product.productName}</td>
<td>{product.productCategory}</td>
<td>{product.supplier}</td>
<td>{product.price}</td>
</tr>
))}
</tbody>
</table>
);
};
export default ProductTable;
In the ProductTable component, we first extract the products array from the props using object destructuring. Then, we create a table element with a thead and tbody. In the thead, we create a table row with table headers for each column: productId, productName, productCategory, supplier, and price. In the tbody, we map through the products array and create a table row for each product. We use the key attribute to assign a unique identifier to each table row. Finally, we display the product information in each table cell.
Map over the
products
array and create a row in the table for each product.Add a button to the component that will call a function called
sortProducts
to sort theproducts
array by price.Add a button to each row in the table that will call a function called
deleteProduct
to remove the corresponding product from theproducts
array.Add a button to each row in the table that will call a function called
editProduct
to edit the corresponding product data.
Searching for Products
In
ProductTable.js
, add an input field for searching byproductId
.Add an
onChangeText
function to the input field that will update a state object calledsearchProductId
.Create a new function called
filterByProductId
that will filter theproducts
array based on thesearchProductId
state object.In the
return
statement ofProductTable.js
, add a conditional statement that will only render rows that match theproductId
search.In
ProductTable.js
, add an input field for searching byproductCategory
.Add an
onChangeText
function to the input field that will update a state object calledsearchProductCategory
.Create a new function called
filterByProductCategory
that will filter theproducts
array based on thesearchProductCategory
state object.In the
return
statement ofProductTable.js
, add a conditional statement that will only render rows that match theproductCategory
search.
Conclusion
Congratulations! You have successfully created a cross-platform application using React Native that allows users to add product information, display the information in a table format, sort the table by price, delete products, edit product data and search for products by product ID and category. Keep practicing and exploring new features to improve your skills!