Database connection in React JS
Create a new React project and navigate to it.
Create-react-app crudop
cd crudop
Start the project by
npm start
Backend ([Link] + Express + MongoDB)
In another terminal , Initialize a new [Link] project:
npm init -y
Install required dependencies
npm install express mongoose cors body-parser
Set up MongoDB (Local or Cloud)
Create a new node file([Link])
Connect with mongodb
**(Here student_db -> student is used)
Use your connection string
And also use your preferred database and collection name
No need to create one , if no database exists then a new one is created
itself.
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
[Link](cors());
[Link]([Link]());
// MongoDB connection
[Link]('mongodb://localhost:27017/student_db', {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => [Link]('MongoDB connected'))
.catch(err => [Link](err));
// Define Student schema
const StudentSchema = new [Link]({
name: String,
rollno: Number,
age: Number,
email: String,
});
const Student = [Link]('Student', StudentSchema);
// CRUD routes
[Link]('/students', async (req, res) => {
const students = await [Link]();
[Link](students);
});
[Link]('/students', async (req, res) => {
const newStudent = new Student([Link]);
await [Link]();
[Link](newStudent);
});
[Link]('/students/:id', async (req, res) => {
const updatedStudent = await [Link]([Link], [Link], {
new: true });
[Link](updatedStudent);
});
[Link]('/students/:id', async (req, res) => {
await [Link]([Link]);
[Link]({ message: 'Student deleted' });
});
// Search for a student by rollno
[Link]('/students/search/:rollno', async (req, res) => {
const student = await [Link]({ rollno: [Link] });
if (student) {
[Link](student);
} else {
[Link](404).json({ message: 'Student not found' });
}
});
// Start server
const PORT = [Link] || 5000;
[Link](PORT, () => [Link](`Server running on port ${PORT}`));
Start the Server
node [Link]
**Server running on port 5000
MongoDB connected**
Now design the frontend
Create a new component in the src ([Link])
import React, { useState} from 'react';
import axios from 'axios';
import './[Link]';
function CrudApp() {
const [students, setStudents] = useState([]);
const [newStudent, setNewStudent] = useState({ name: '', rollno: '', age: '',
email: '' });
const [editing, setEditing] = useState(null);
const [editingStudent, setEditingStudent] = useState({});
const [searchRollno, setSearchRollno] = useState('');
const [searchResult, setSearchResult] = useState(null);
const fetchStudents = async () => {
const response = await [Link]('[Link]
const sortedStudents = [Link]((a, b) =>
[Link]([Link]));
setStudents(sortedStudents);
};
const addStudent = async () => {
if ([Link] && [Link] && [Link] &&
[Link]) {
const response = await [Link]('[Link]
newStudent);
setStudents([...students, [Link]].sort((a, b) =>
[Link]([Link])));
setNewStudent({ name: '', rollno: '', age: '', email: '' });
}
};
const deleteStudent = async (id) => {
await [Link](`[Link]
setStudents([Link](student => student._id !== id));
};
const updateStudent = async (id) => {
if ([Link] && [Link] && [Link] &&
[Link]) {
const response = await [Link](`[Link]
editingStudent);
setStudents([Link](student => (student._id === id ? [Link] :
student)).sort((a, b) => [Link]([Link])));
setEditing(null);
setEditingStudent({});
}
};
const searchByRollno = async () => {
try {
const response = await
[Link](`[Link]
setSearchResult([Link]);
} catch (error) {
setSearchResult(null);
[Link]('Student not found');
}
};
return (
<div className="container">
<h1>Student Database CRUD</h1>
{/* Add New Student */}
<div className="form-group">
<h2>Add Student</h2>
<input
type="text"
placeholder="Name"
value={[Link]}
onChange={(e) => setNewStudent({ ...newStudent, name: [Link]
})}
/>
<input
type="number"
placeholder="Roll No"
value={[Link]}
onChange={(e) => setNewStudent({ ...newStudent, rollno: [Link]
})}
/>
<input
type="number"
placeholder="Age"
value={[Link]}
onChange={(e) => setNewStudent({ ...newStudent, age: [Link] })}
/>
<input
type="email"
placeholder="Email"
value={[Link]}
onChange={(e) => setNewStudent({ ...newStudent, email: [Link]
})}
/>
<button className="btn" onClick={addStudent}>Add Student</button>
</div>
{/* Search Student by Rollno */}
<div className="form-group">
<h2>Search by Roll No</h2>
<input
type="number"
placeholder="Enter Roll No"
value={searchRollno}
onChange={(e) => setSearchRollno([Link])}
/>
<button className="btn" onClick={searchByRollno}>Search</button>
{searchResult && (
<div className="card">
<h3>Search Result:</h3>
<p><strong>Name:</strong> {[Link]}</p>
<p><strong>Roll No:</strong> {[Link]}</p>
<p><strong>Age:</strong> {[Link]}</p>
<p><strong>Email:</strong> {[Link]}</p>
</div>
)}
</div>
<button className="btn" onClick={fetchStudents}>See all students</button>
{/* List of Students */}
<ul>
{[Link](student => (
<li key={student._id}>
{editing === student._id ? (
<div>
<input
type="text"
value={[Link]}
onChange={(e) => setEditingStudent({ ...editingStudent, name:
[Link] })}
placeholder="Edit Name"
/>
<input
type="number"
value={[Link]}
onChange={(e) => setEditingStudent({ ...editingStudent, rollno:
[Link] })}
placeholder="Edit Roll No"
/>
<input
type="number"
value={[Link]}
onChange={(e) => setEditingStudent({ ...editingStudent, age:
[Link] })}
placeholder="Edit Age"
/>
<input
type="email"
value={[Link]}
onChange={(e) => setEditingStudent({ ...editingStudent, email:
[Link] })}
placeholder="Edit Email"
/>
<button onClick={() => updateStudent(student._id)}>Save</button>
<button onClick={() => setEditing(null)}>Cancel</button>
</div>
) : (
<div className="card">
{[Link]} <button onClick={() => { setEditing(student._id);
setEditingStudent(student); }}>Edit</button>
<button onClick={() =>
deleteStudent(student._id)}>Delete</button>
<br />Roll No: {[Link]},<br />Age: {[Link]},<br
/>Email: {[Link]}<br /><br />
</div>
)}
</li>
))}
</ul>
</div>
);
}
export default CrudApp;
Add your css to design the page .
Add the component to your [Link]
import React from 'react';
import CrudApp from './CrudApp';
function App() {
return (
<div className="App">
<CrudApp />
</div>
);
}
export default App;
The output will be like this..
Create
Read
Update
Delete
Changes will be reflected in your mongo db