0% found this document useful (0 votes)
12 views14 pages

Database Connection in React JS

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views14 pages

Database Connection in React JS

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

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 (Node.js + Express + MongoDB)


In another terminal , Initialize a new Node.js 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(server.js)

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();


app.use(cors());
app.use(bodyParser.json());

// MongoDB connection
mongoose.connect('mongodb://localhost:27017/student_db', {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log('MongoDB connected'))
.catch(err => console.error(err));
// Define Student schema
const StudentSchema = new mongoose.Schema({
name: String,
rollno: Number,
age: Number,
email: String,
});

const Student = mongoose.model('Student', StudentSchema);

// CRUD routes
app.get('/students', async (req, res) => {
const students = await Student.find();
res.json(students);
});

app.post('/students', async (req, res) => {


const newStudent = new Student(req.body);
await newStudent.save();
res.json(newStudent);
});

app.put('/students/:id', async (req, res) => {


const updatedStudent = await Student.findByIdAndUpdate(req.params.id, req.body, {
new: true });
res.json(updatedStudent);
});

app.delete('/students/:id', async (req, res) => {


await Student.findByIdAndDelete(req.params.id);
res.json({ message: 'Student deleted' });
});

// Search for a student by rollno


app.get('/students/search/:rollno', async (req, res) => {
const student = await Student.findOne({ rollno: req.params.rollno });
if (student) {
res.json(student);
} else {
res.status(404).json({ message: 'Student not found' });
}
});

// Start server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Start the Server

node server.js

**Server running on port 5000


MongoDB connected**

Now design the frontend


Create a new component in the src (CrudApp.js)

import React, { useState} from 'react';


import axios from 'axios';
import './CrudApp.css';

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 axios.get('http://localhost:5000/students');
const sortedStudents = response.data.sort((a, b) =>
a.name.localeCompare(b.name));
setStudents(sortedStudents);
};

const addStudent = async () => {


if (newStudent.name && newStudent.rollno && newStudent.age &&
newStudent.email) {
const response = await axios.post('http://localhost:5000/students',
newStudent);
setStudents([...students, response.data].sort((a, b) =>
a.name.localeCompare(b.name)));
setNewStudent({ name: '', rollno: '', age: '', email: '' });
}
};

const deleteStudent = async (id) => {


await axios.delete(`http://localhost:5000/students/${id}`);
setStudents(students.filter(student => student._id !== id));
};

const updateStudent = async (id) => {


if (editingStudent.name && editingStudent.rollno && editingStudent.age &&
editingStudent.email) {
const response = await axios.put(`http://localhost:5000/students/${id}`,
editingStudent);
setStudents(students.map(student => (student._id === id ? response.data :
student)).sort((a, b) => a.name.localeCompare(b.name)));
setEditing(null);
setEditingStudent({});
}
};

const searchByRollno = async () => {


try {
const response = await
axios.get(`http://localhost:5000/students/search/${searchRollno}`);
setSearchResult(response.data);
} catch (error) {
setSearchResult(null);
console.error('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={newStudent.name}
onChange={(e) => setNewStudent({ ...newStudent, name: e.target.value
})}
/>
<input
type="number"
placeholder="Roll No"
value={newStudent.rollno}
onChange={(e) => setNewStudent({ ...newStudent, rollno: e.target.value
})}
/>
<input
type="number"
placeholder="Age"
value={newStudent.age}
onChange={(e) => setNewStudent({ ...newStudent, age: e.target.value })}
/>
<input
type="email"
placeholder="Email"
value={newStudent.email}
onChange={(e) => setNewStudent({ ...newStudent, email: e.target.value
})}
/>
<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(e.target.value)}
/>
<button className="btn" onClick={searchByRollno}>Search</button>

{searchResult && (
<div className="card">
<h3>Search Result:</h3>
<p><strong>Name:</strong> {searchResult.name}</p>
<p><strong>Roll No:</strong> {searchResult.rollno}</p>
<p><strong>Age:</strong> {searchResult.age}</p>
<p><strong>Email:</strong> {searchResult.email}</p>
</div>
)}

</div>

<button className="btn" onClick={fetchStudents}>See all students</button>

{/* List of Students */}


<ul>
{students.map(student => (
<li key={student._id}>
{editing === student._id ? (
<div>
<input
type="text"
value={editingStudent.name}
onChange={(e) => setEditingStudent({ ...editingStudent, name:
e.target.value })}
placeholder="Edit Name"
/>
<input
type="number"
value={editingStudent.rollno}
onChange={(e) => setEditingStudent({ ...editingStudent, rollno:
e.target.value })}
placeholder="Edit Roll No"
/>
<input
type="number"
value={editingStudent.age}
onChange={(e) => setEditingStudent({ ...editingStudent, age:
e.target.value })}
placeholder="Edit Age"
/>
<input
type="email"
value={editingStudent.email}
onChange={(e) => setEditingStudent({ ...editingStudent, email:
e.target.value })}
placeholder="Edit Email"
/>
<button onClick={() => updateStudent(student._id)}>Save</button>
<button onClick={() => setEditing(null)}>Cancel</button>
</div>
) : (
<div className="card">
{student.name} <button onClick={() => { setEditing(student._id);
setEditingStudent(student); }}>Edit</button>
<button onClick={() =>
deleteStudent(student._id)}>Delete</button>
<br />Roll No: {student.rollno},<br />Age: {student.age},<br
/>Email: {student.email}<br /><br />
</div>
)}
</li>
))}
</ul>
</div>
);
}

export default CrudApp;

Add your css to design the page .

Add the component to your App.js


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

You might also like