Reactjs Curd Operation
Ravi Rajput
Software Engineer | Angular Expert | ReactJs | Javascript | C# | DotNet Core |.net Maui | DevOps | Fullstack Developer
Hi, I am Writing Here curd operation code in ReactJs, if you want you can implement.
first create your project , i hope you know very well how to create react js app.
npx create-react-app curdapp and, cd curdapp then,npm start and then install
npm install semantic-ui-react semantic-ui-css
import the library in your app's main entry file, which is index.js.
and @import url('https://fonts.googleapis.com/css2?family=Montserrat&display=swap'); apply inside app.css
and
npm i axios to install this package. for use Axios to send our form data to the mock server.
so now i am sharing code.
index.js
领英推è
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'semantic-ui-css/semantic.min.css'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
and
app.js
import './App.css'; import Create from './components/create'; import Read from './components/read'; import Update from './components/update'; import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom'; function App() { return ( <Router> <div className="main"> <h2 className="main-header">React CRUD Operations</h2> <div className="navigation"> <Link to="/create"> <button>Create</button> </Link> <Link to="/read"> <button>Read</button> </Link> <Link to="/update"> <button>Update</button> </Link> </div> <div> <Routes> <Route exact path='/create' element={<Create />} /> <Route exact path='/read' element={<Read />} /> <Route path='/update' element={<Update />} /> </Routes> </div> </div> </Router> ); } export default App;
and
create.js,
import React, { useState } from 'react'; import { Button, Checkbox, Form } from 'semantic-ui-react'; import axios from 'axios'; import { useNavigate } from 'react-router-dom'; export default function Create() { let navigate = useNavigate(); const [firstName, setFirstName] = useState(''); const [lastName, setLastName] = useState(''); const [checkbox, setCheckbox] = useState(false); const postData = (e) => { e.preventDefault(); axios.post(`https://67061c1f031fd46a8311f820.mockapi.io/fakedata`, { firstName, lastName, checkbox }) .then(() => { navigate('/read'); }) .catch((error) => { console.error("Error posting data: ", error); }); }; return ( <div> <Form className="create-form" onSubmit={postData}> <Form.Field> <label>First Name</label> <input placeholder='First Name' value={firstName} onChange={(e) => setFirstName(e.target.value)} /> </Form.Field> <Form.Field> <label>Last Name</label> <input placeholder='Last Name' value={lastName} onChange={(e) => setLastName(e.target.value)} /> </Form.Field> <Form.Field> <Checkbox label='I agree to the Terms and Conditions' checked={checkbox} onChange={() => setCheckbox(!checkbox)} /> </Form.Field> <Button type='submit'>Submit</Button> </Form> </div> ); }
and read.js
import React, { useEffect, useState } from 'react'; import { Table, Button } from 'semantic-ui-react'; import { Link } from 'react-router-dom'; import axios from 'axios'; export default function Read() { const [APIData, setAPIData] = useState([]); useEffect(() => { fetchData(); }, []); const fetchData = () => { axios.get(`https://67061c1f031fd46a8311f820.mockapi.io/fakedata`) .then((response) => { setAPIData(response.data); }) .catch((error) => { console.error("Error fetching data: ", error); }); }; const setData = (data) => { let { id, firstName, lastName, checkbox } = data; localStorage.setItem('ID', id); localStorage.setItem('First Name', firstName); localStorage.setItem('Last Name', lastName); localStorage.setItem('Checkbox Value', checkbox); }; const onDelete = (id) => { axios.delete(`https://67061c1f031fd46a8311f820.mockapi.io/fakedata/${id}`) .then(() => { setAPIData((prevData) => prevData.filter((data) => data.id !== id)); }) .catch((error) => { console.error("Error deleting data: ", error); }); }; return ( <div> <Table singleLine> <Table.Header> <Table.Row> <Table.HeaderCell>First Name</Table.HeaderCell> <Table.HeaderCell>Last Name</Table.HeaderCell> <Table.HeaderCell>Checkbox Value</Table.HeaderCell> <Table.HeaderCell>Update</Table.HeaderCell> <Table.HeaderCell>Delete</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> {APIData.map((data) => ( <Table.Row key={data.id}> <Table.Cell>{data.firstName}</Table.Cell> <Table.Cell>{data.lastName}</Table.Cell> <Table.Cell>{data.checkbox ? 'Checked' : 'Unchecked'}</Table.Cell> <Table.Cell> <Link to='/update'> <Button onClick={() => setData(data)}>Update</Button> </Link> </Table.Cell> <Table.Cell> <Button onClick={() => onDelete(data.id)}>Delete</Button> </Table.Cell> </Table.Row> ))} </Table.Body> </Table> </div> ); }
and
update.js
import React, { useState, useEffect } from 'react';
import { Button, Checkbox, Form } from 'semantic-ui-react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
export default function Update() {
let navigate = useNavigate();
const [id, setID] = useState(null);
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [checkbox, setCheckbox] = useState(false);
useEffect(() => {
const storedID = localStorage.getItem('ID');
setID(storedID);
setFirstName(localStorage.getItem('First Name'));
setLastName(localStorage.getItem('Last Name'));
setCheckbox(localStorage.getItem('Checkbox Value') === 'true');
console.log("Current ID:", storedID); // Log the ID
}, []);
const updateAPIData = (e) => {
e.preventDefault();
if (!id) {
console.error("No ID found in local storage.");
return; // Prevent the request if the ID is not available
}
axios.put(`https://67061c1f031fd46a8311f820.mockapi.io/fakedata/${id}`, {
firstName,
lastName,
checkbox
})
.then(() => {
navigate('/read');
})
.catch((error) => {
console.error("Error updating data: ", error.response ? error.response.data : error.message);
});
};
return (
<div>
<Form className="create-form" onSubmit={updateAPIData}>
<Form.Field>
<label>First Name</label>
<input
placeholder='First Name'
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
/>
</Form.Field>
<Form.Field>
<label>Last Name</label>
<input
placeholder='Last Name'
value={lastName}
onChange={(e) => setLastName(e.target.value)}
/>
</Form.Field>
<Form.Field>
<Checkbox
label='I agree to the Terms and Conditions'
checked={checkbox}
onChange={() => setCheckbox(!checkbox)}
/>
</Form.Field>
<Button type='submit'>Update</Button>
</Form>
</div>
);
}
and
app.css
@import url('https://fonts.googleapis.com/css2?family=Montserrat&display=swap'); .main { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #212121; color: rgb(247, 13, 13); flex-direction: column; } .main-header { font-family: 'Montserrat', sans-serif; } .create-form label { color: whitesmoke !important; font-family: 'Montserrat', sans-serif; font-size: 12px !important; }
please use this code, you can create curd oeperation in Reactjs