In this article, we will implement CRUD operation in ReactJS(v18) application.
Command to create ReactJS application
(Step 1)
Now add routing for each ReactJS component at the 'App' component.
(Step 2)
ReactJS:
ReactJS is a javascript library for creating user interface components. ReactJS components contains javascript function and they return JSX(JavaScript XML) as output. ReactJS effectively renders and update component on data changes.
Create ReactJS(v18) Application:
To create a ReactJS application our local machine should contain NodeJS. So go to 'https://nodejs.org/en/download/'
npx create-react-app name-of-your-app
Command to start the application.
npm start
Let's go through the project and explore important files.
index.html: Inside the public folder we can see the index.html. Only the HTML file of the entire ReactJS application. It contained a 'div' element whose 'id' value is 'root', inside of this element all ReactJS components get rendered.
index.js: Entry javascript file for ReactJS. It helps paint 'App' component content in 'index.html'.
index.html: Inside the public folder we can see the index.html. Only the HTML file of the entire ReactJS application. It contained a 'div' element whose 'id' value is 'root', inside of this element all ReactJS components get rendered.
index.js: Entry javascript file for ReactJS. It helps paint 'App' component content in 'index.html'.
App.js: The 'App.js' react component. It returns the 'JSX'(Javascript XML) content(JSX means writing the HTML code inside of javascript directly).
Install ReactJS Bootstrap:
ReactJS Bootstrap library built on top of normal bootstrap. ReactJS Bootstrap UI components are very easy to integrate with the ReactJS app.
npm install react-bootstrap bootstrap
Now add the bootstrap CSS file reference to the 'index.js'
src/index.js:
import React from "react"; import ReactDOM from "react-dom/client"; import "./index.css"; import App from "./App"; import "bootstrap/dist/css/bootstrap.min.cs"; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<App />);
- (Line: 5) Added the bootstrap CSS file reference.
- Here we removed the existing code like 'reportWebVitals' and 'React.StrictMode'.
Add React Bootstrap Menu:
Now, 'Menu' will be shared content must be displayed for every page on the application. So let's create a shared component like 'Layout.js' inside of the 'components/shared' folders(new folders).
src/component/shared/Layout.js:
import Container from 'react-bootstrap/Container'; import Navbar from 'react-bootstrap/Navbar'; function Layout(props) { return ( <div> <Navbar expand="lg" variant="dark" bg="success"> <Container> <Navbar.Brand >Fruits Bucket</Navbar.Brand> </Container> </Navbar> <Container>{props.children}</Container> </div> ); } export default Layout;
- Here 'Layout' is our component function entire logic is added inside of it and this function returns JSX content. The 'Layout' function has input parameters like 'props' which gives access to either custom or default properties.
- (Line: 1&2) Imported the react-bootstrap component like 'Container' & 'Navbar'.
- (Line: 12) The 'Layout' function must be render as custom tag like '<Layout></Layout>'. So to read the content inside of the 'Layout' element we have to use 'props.children' and to render the content we have to use ReactJS expression like '{}'(this can render plain text, HTML, and even executes logical expressions).
src/App.js:
import "./App.css"; import Layout from "./components/shared/Layout"; function App() { return <Layout><h1>Welcome!</h1></Layout>; } export default App;
Setup JSON Server:
Let's set up a fake API by setting up the JSON server in our local machine.
Run the below command to install the JSON server globally onto your local system.
npm install -g json-server
For our demo purpose go to the ReactJS application and the following command to the 'package.json' file. By default, the JSON server runs on port number 3000, ReactJS also runs on the same portal locally so here we specify another port number explicitly.
"json-server":"json-server --watch db.json --port 4000"
Now to invoke the above command run the following command in the ReactJS app root folder.
npm run json-server
After running the above command for the first time, a 'db.json' file gets created, so this file act as a database. So let's add some sample data to the file below.
Now access the API endpoint like 'http://localhost:4000/fruits'.
Create A ReactJS Component 'AllFruits':
Let's create a new ReactJS component like 'AllFruits' inside of the new folder 'pages'.
src/pages/AllFruits.js:
function AllFruits() { return <></>; } export default AllFruits;
Install Axios Library:
To invoke the API calls from our ReactJS application most recommended library is 'Axios'. Let's install the 'Axios' library
npm i axios
Display API Response In 'AllFruits' Component(Read Operation):
Let's implement the Read Operation by invoking the API call and then render the response in the 'AllFruits' component.
src/pages/AllFruits.js:
import axios from "axios"; import { useEffect, useState } from "react"; import Card from "react-bootstrap/Card"; import Col from "react-bootstrap/Col"; import Row from "react-bootstrap/Row"; function AllFruits() { const [allFruits, setAllFruits] = useState([]); useEffect(() => { axios.get("http://localhost:4000/fruits").then((response) => { setAllFruits(response.data); }); }, []); return ( <> <Row xs={1} md={3} className="g-2"> {allFruits.map((item) => ( <Col key={item.id}> <Card> <Card.Img variant="top" src={item.imageUrl} /> <Card.Body> <Card.Title>{item.name}</Card.Title> <Card.Text>Quantity(KG Units) - {item.quantity}</Card.Text> <Card.Text>Price - {item.price}</Card.Text> </Card.Body> </Card> </Col> ))} </Row> </> ); } export default AllFruits;
- The 'useState' loads from the 'react' library. In ReactJS application to maintain a state of data, we will use the 'useState'. If the value of 'useState' variable changes entire component gets refreshed(reexecutes). The default values can be given while it is initialized. The 'useState' return array of 2 values, where the first value will be the data and the second value will be the function to update the state.
- The 'useEffect' loads from the 'react' library. The 'useEffect(() => {},[])' contains 2 input parameters where first parameter is arrow function in which we can write our logic to executes and second parameter is array to which we can pass 'useState' values. So whenever the second parameter value changes then only the 'useEffect' gets executed. If the second parameter array is empty then 'useEffect' get executes only once.
- (Line: 8) Declared the 'useState' where its value will be accessed through 'allFruits' and to update it we have to use the'setAllFurits' function.
- (Line: 10-14) Here used the 'useEffect' where we implemented our Axois API call logic. So to execute the logic inside of 'useEffect' only once we passed the second parameter as an empty array. After API success the response is assigned to 'allFruits' by setting the 'setAllFruits'.
- (Line: 18) Used ReactJS bootstrap 'Row' component and specified its property like 'md={3}' only render 3 columns from medium size screens and another property like 'xs={1}' only reander 1 column for extra-small screens(mobiles).
- (Line: 19) The 'allFruits' state variable which contains API response is looping to render the data.
- (Line: 20) The 'Col' component specified the 'key' property which is recommended to provide unique value for looping items.
- (Line: 22-26) In ReactJS to render dynamic data, we have used single flower braces '{}'.
src/App.js:
import "./App.css"; import Layout from "./components/shared/Layout"; import AllFruits from "./pages/AllFruits"; function App() { return ( <Layout> <AllFruits></AllFruits> </Layout> ); } export default App;Now run our ReactJ application and our JSON server.
(Step 1)
(Step 2)
Create A ReactJS Component 'AddFruit':
In the 'pages' folder let's add a new ReactJS component like 'AddFruit'.
src/pages/AddFruit.js:
function AddFruit() { return <></>; } export default AddFruit;
Install React Router Package And Configure Routes:
Let's install the React Router package.
npm i react-router-dom
src/App.js:
import { Routes, Route } from "react-router-dom"; import "./App.css"; import Layout from "./components/shared/Layout"; import AddFruit from "./pages/AddFruit"; import AllFruits from "./pages/AllFruits"; function App() { return ( <Layout> <Routes> <Route path="/" element={<AllFruits />}></Route> <Route path="/add-fruit" element={<AddFruit />}></Route> </Routes> </Layout> ); } export default App;
- Here 'Routes', and 'Route' components are loading from the 'react-router-dom'.
- Inside of our 'Layout' component add the 'Routes' component and 'Route' are its child component.
- For each 'Route' component, we set up properties like 'path' to configure the route and an 'element' to map the component that needs load for the matching route.
src/index.js:
import React from "react"; import ReactDOM from "react-dom/client"; import "./index.css"; import App from "./App"; import "bootstrap/dist/css/bootstrap.min.css"; import { BrowserRouter } from "react-router-dom"; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<BrowserRouter><App /></BrowserRouter>);
Create Form To Consume HTTP Post API Call In 'AddFruit' Component(Create Operation):
Let's implement the logic to create a new item by invoking the HTTP Post API call in the 'AddFruit' component.
src/pages/AddFruit.js:
import axios from "axios"; import { useRef } from "react"; import Button from "react-bootstrap/Button"; import Form from "react-bootstrap/Form"; import { useNavigate } from "react-router-dom"; function AddFruit() { const fruitName = useRef(""); const quantity = useRef(""); const price = useRef(""); const imageUrl = useRef(""); const navigate = useNavigate(); const addFruitHandler = () => { var payload = { name: fruitName.current.value, quantity: quantity.current.value? Number(quantity.current.value):0, price: price.current.value ? Number(price.current.value): 0 , imageUrl: imageUrl.current.value, }; axios.post("http://localhost:4000/fruits", payload).then(() => { navigate("/"); }); }; return ( <> <legend>Create</legend> <Form> <Form.Group className="mb-3" controlId="formName"> <Form.Label>Name</Form.Label> <Form.Control type="text" ref={fruitName} /> </Form.Group> <Form.Group className="mb-3" controlId="formQuanity"> <Form.Label>Quantity(KG Units)</Form.Label> <Form.Control type="number" ref={quantity} /> </Form.Group> <Form.Group className="mb-3" controlId="formPrice"> <Form.Label>Price</Form.Label> <Form.Control type="number" ref={price} /> </Form.Group> <Form.Group className="mb-3" controlId="formImageUrl"> <Form.Label>ImageUrl</Form.Label> <Form.Control type="text" ref={imageUrl} /> </Form.Group> <Button variant="primary" type="button" onClick={addFruitHandler}> Add </Button> </Form> </> ); } export default AddFruit;
- The 'useRef' loads from the 'react' library. The 'useRef' can be used to read the instance of the HTML elements.
- (Line: 8-11) Declared and initialized the 'useRef' variable, each variable represents a form field for reading the user entered form data.
- (Line: 13) Declared 'navigate' variable of type 'useNavigate()'. The 'useNaviget()' loads from the 'react-router-dom'. It helps navigate between the react components.
- (Line: 15-25) Add the 'addFruitHandler' method, it contains logic to invoke the API call to create a new item. Here payload is prepared with our 'useRef' variable from which we fetch form data. On the success of API call navigate back to home page.
- (Line: 32&36&40&44) Here 'Form.Control' decorated with 'ref' attribute that is assigned to our 'useRef' variables. So 'ref' attribute passes the HTML element instances to the 'useRef' variables.
- (Line: 46-48) The 'Add' button whose 'onclick' registered to 'addFruitHandler' method.
src/pages/AllFruits.js:
import axios from "axios"; import { useEffect, useState } from "react"; import Card from "react-bootstrap/Card"; import Col from "react-bootstrap/Col"; import Row from "react-bootstrap/Row"; import { useNavigate } from "react-router-dom"; import Button from "react-bootstrap/Button"; function AllFruits() { const [allFruits, setAllFruits] = useState([]); const navigate = useNavigate(); useEffect(() => { axios.get("http://localhost:4000/fruits").then((response) => { setAllFruits(response.data); }); }, []); return ( <> <Row className="mt-2"> <Col md={{ span: 4, offset: 4 }}> <Button variant="primary" onClick={() => navigate("/add-fruit")}> Add New Fruit </Button> </Col> </Row> <Row xs={1} md={3} className="g-2"> {allFruits.map((item) => ( <Col key={item.id}> <Card > <Card.Img variant="top" src={item.imageUrl} style={{height:300}} /> <Card.Body> <Card.Title>{item.name}</Card.Title> <Card.Text>Quantity(KG Units) - {item.quantity}</Card.Text> <Card.Text>Price - {item.price}</Card.Text> </Card.Body> </Card> </Col> ))} </Row> </> ); } export default AllFruits;
- (Line: 11) Declared the 'navigate' variable of type 'useNavigate()'. The 'useNavigate()' loads from the 'react-router-dom'.
- (Line: 23-25) Configured the 'Add New Fruit' button whose 'onClick' event registers with an arrow function that contains navigation logic.
(Step 2)
(Step 3)
Create A ReactJS Component 'UpdateFruit':
In the 'pages' folder let's add a new ReactJS component like 'UpdateFruit'.
src/pages/UpdateFruit.js:
function UpdateFruit() { return <></>; } export default UpdateFruit;Now configure the route for the 'UpdateFruit' component in the 'App' component.
src/App.js:
import { Routes, Route } from "react-router-dom"; import "./App.css"; import Layout from "./components/shared/Layout"; import AddFruit from "./pages/AddFruit"; import AllFruits from "./pages/AllFruits"; import UpdateFruit from "./pages/UpdateFruit"; function App() { return ( <Layout> <Routes> <Route path="/" element={<AllFruits />}></Route> <Route path="/add-fruit" element={<AddFruit />}></Route> <Route path="/update-fruit/:id" element={<UpdateFruit />}></Route> </Routes> </Layout> ); } export default App;
- (Line: 14) Configured route for 'UpdateFruit' component. Here we can observe dynamic route placeholders like ':id' which means our item 'id' value will be passed.
Edit Form To Consume HTTP Put API Call In 'UpdateFruit' Component(Update Operation):
Let's implement the 'Edit' form in the 'UpdateFruit' component on the submitting form send the data to the HTTP Put endpoint.
src/pages/UpdateFruit.js:
import axios from "axios"; import { useEffect, useRef } from "react"; import { useNavigate, useParams } from "react-router-dom"; import Button from "react-bootstrap/Button"; import Form from "react-bootstrap/Form"; function UpdateFruit() { const fruitName = useRef(""); const quantity = useRef(""); const price = useRef(""); const imageUrl = useRef(""); const { id } = useParams(); const navigate = useNavigate(); useEffect(() => { axios.get(`http://localhost:4000/fruits/${id}`).then((response) => { fruitName.current.value = response.data.name; quantity.current.value = response.data.quantity; price.current.value = response.data.price; imageUrl.current.value = response.data.imageUrl; }); }, []); const updateFruitHandler = () => { var payload = { name: fruitName.current.value, quantity: quantity.current.value ? Number(quantity.current.value) : 0, price: price.current.value ? Number(price.current.value) : 0, imageUrl: imageUrl.current.value, }; axios.put(`http://localhost:4000/fruits/${id}`, payload).then((response) => { navigate("/"); }) }; return ( <> <legend>Update</legend> <Form> <Form.Group className="mb-3" controlId="formName"> <Form.Label>Name</Form.Label> <Form.Control type="text" ref={fruitName} /> </Form.Group> <Form.Group className="mb-3" controlId="formQuanity"> <Form.Label>Quantity(KG Units)</Form.Label> <Form.Control type="number" ref={quantity} /> </Form.Group> <Form.Group className="mb-3" controlId="formPrice"> <Form.Label>Price</Form.Label> <Form.Control type="number" ref={price} /> </Form.Group> <Form.Group className="mb-3" controlId="formImageUrl"> <Form.Label>ImageUrl</Form.Label> <Form.Control type="text" ref={imageUrl} /> </Form.Group> <Button variant="primary" type="button" onClick={updateFruitHandler}> Update </Button> </Form> </> ); } export default UpdateFruit;
- (Line: 8-11) Declared the 'useRef' variables which we use to read the form data.
- (Line: 13) The 'useParams()' loads from the 'react-router-dom' helps to read the dynamic data from the route.
- (Line: 15) Declared 'navigate' variable of type 'useNavigate()'.
- (Line: 17-24) Here invoking the API by the 'id' value. It needs to be invoked only once on component rendering so it's invoked inside of the 'useEffect'.
- (Line: 26-37) Created the 'updateFruitHandler' method which invokes HTTP PUT API call.
- (Line: 59-60) Configured 'Update' button whose click event registered with 'updateFruitHandler'.
src/pages/AllFruits.js:
// existing code hidden for display purpose <Card.Body> <Card.Title>{item.name}</Card.Title> <Card.Text>Quantity(KG Units) - {item.quantity}</Card.Text> <Card.Text>Price - {item.price}</Card.Text> <Button variant="primary" onClick={() => navigate(`/update-fruit/${item.id}`)} > Edit </Button> </Card.Body>
- (Line: 6-11) The 'Edit' button click event registered with the arrow function. The arrow function contains logic to navigate to 'UpdateFruit' component.
(Step 2)
(Step 3)
Create 'DeleteConfirmation' React Component:
Let's create a new React component like 'DeleteConfirmation'. This is not going to be a page component, but i want make it as a shared component so that anywhere we can use this 'DeleteConfiramtion' component so create this component in 'components/shared' folders.
src/components/shared/DeleteConfirmation.js:
import Button from "react-bootstrap/Button"; import Modal from "react-bootstrap/Modal"; function DeleteConfirmation(props) { return ( <> <Modal show={props.showModal} onHide={() => { props.hideDeleteModalHandler(); }} > <Modal.Header closeButton> <Modal.Title>{props.title}</Modal.Title> </Modal.Header> <Modal.Body>{props.body}</Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={() => { props.hideDeleteModalHandler(); }} > Close </Button> <Button variant="primary" onClick={() => { props.confirmDeleteHandler(); }} > Confirm Delete </Button> </Modal.Footer> </Modal> </> ); } export default DeleteConfirmation;
- Here 'DeleteConfirmation' component contains react-bootstrap modal code.
- (Line: 8) The 'show' is the boolean property of the 'Modal' component. The parent component passes its value through 'props.showModal'(here showModal is our custom property name which must be passed by the parent component and its value should be boolean). So if 'show' property receives 'true' then opens the modal.
- (Line: 9-11) The 'onHide' get triggered by the 'X'(close button) on the rigth-top corner of the modal. Here 'onHide' register with an arrow function which internally calls a method of the parent component like 'props.hideDeleteModalHandler'.
- (Line: 14) Dynamic 'props.title' property for the modal title.
- (Line: 16) Dynamic 'props.body' property for the modal body.
- (Line: 18-25) Close button click event register with arrow function which internally calls a method of parents component like 'props.hideDeleteModalHandler'.
- (Line: 26-33) Confirm delete button, click event register with arrow function which internally calls a method of parents component like 'props.confirmDeleteHandler'.
Invoke 'DeleteConfirmation' From 'AllFruits' Component(Delete Operation):
Let's add the 'DeleteConfirmation' element into our 'AllFruits' component so that whenever we click on the delete button 'DeleteConfimation' modal will open.
src/pates/AllFruits.js:
import axios from "axios"; import { useEffect, useState } from "react"; import Card from "react-bootstrap/Card"; import Col from "react-bootstrap/Col"; import Row from "react-bootstrap/Row"; import { useNavigate } from "react-router-dom"; import Button from "react-bootstrap/Button"; import DeleteConfirmation from "../components/shared/DeleteConfirmation"; function AllFruits() { const [allFruits, setAllFruits] = useState([]); const navigate = useNavigate(); const [showModal, setShowModal] = useState(false); const [itemToDeleteId, setItemToDeleteId] = useState(0); useEffect(() => { axios.get("http://localhost:4000/fruits").then((response) => { setAllFruits(response.data); }); }, []); const openConfirmDeleteModalHandler = (id) => { setShowModal(true); setItemToDeleteId(id); }; const hideDeleteModalHandler = () => { setShowModal(false); setItemToDeleteId(0); }; const confirmDeleteHandler = () => { axios .delete(`http://localhost:4000/fruits/${itemToDeleteId}`) .then((response) => { setAllFruits((previousState) => { return previousState.filter((_) => _.id !== itemToDeleteId); }); setItemToDeleteId(0); setShowModal(false); }); }; return ( <> <DeleteConfirmation showModal={showModal} hideDeleteModalHandler={hideDeleteModalHandler} title="Delete Confirmation" body="Are you want delete this itme?" confirmDeleteHandler={confirmDeleteHandler} ></DeleteConfirmation> <Row className="mt-2"> <Col md={{ span: 4, offset: 4 }}> <Button variant="primary" onClick={() => navigate("/add-fruit")}> Add New Fruit </Button> </Col> </Row> <Row xs={1} md={3} className="g-2"> {allFruits.map((item) => ( <Col key={item.id}> <Card> <Card.Img variant="top" src={item.imageUrl} style={{ height: 300 }} /> <Card.Body> <Card.Title>{item.name}</Card.Title> <Card.Text>Quantity(KG Units) - {item.quantity}</Card.Text> <Card.Text>Price - {item.price}</Card.Text> <Button variant="primary" onClick={() => navigate(`/update-fruit/${item.id}`)} > Edit </Button> <Button variant="danger" onClick={() =>{openConfirmDeleteModalHandler(item.id)}} > Delete </Button> </Card.Body> </Card> </Col> ))} </Row> </> ); } export default AllFruits;
- (Line: 14) The 'showModal' & 'setShowModal' are useState variables used to show and hide the Modal
- (Line: 15) The 'itemToDeleteId' & 'setItemToDeleteId' are useState variables used to maintain 'id' of the record need to be deleted.
- (Line: 23-26) The function 'openConfirmDeleteModalHandler' will invoke by the delete button. It contains logic like 'setShowModal' to true which opens the delete confirmation modal and 'setItemToDelteId' contains the record to be deleted
- (Line: 28-31) The function 'hideDeleteModalHandler' will invoke by the 'cancel' button on modal. It contains logic like 'setShowModal' to false which closes the modal and 'setItemToDeleteId' reset to value '0'.
- (Line: 33-43) The function 'confirmDeleteHandler' logic invokes the delete API call. After API success we are updating a few 'useState' variables. The 'setShowModal' is assigned to false to close the modal. The 'setAllFruits' update to remove the deleted item from its array. The 'setItemToDeleteId' value reset to '0'
- (Line: 47-52) Rendered the 'DeleteConfirmation' component element with all required props
- (Line: 80-85) The 'Delete' button clicks the event registered with the arrow function it internally invoke the 'openConfirmDeleteModalHandler' by inputting the 'id' of the item to delete.
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping Up:
Hopefully, I think this article delivered some useful information on the React JS(v18) CRUD Example. I love to have your feedback, suggestions, and better techniques in the comment section below.
Comments
Post a Comment