To connect a React app to a database

Spread the love

To connect a React app to a database, you’ll need to integrate the frontend with a backend that manages the database connections (MongoDB, MySQL, SQLite). React doesn’t directly connect to databases; it communicates with a backend server (using Express, for example) that interacts with the database.

Here’s a step-by-step guide to set up a basic backend using Express for MongoDB, MySQL, and SQLite. The backend will expose APIs that your React frontend can call to interact with the database.

1. Setting Up the Backend (Node.js + Express)

First, we’ll need to set up a Node.js backend with Express that connects to MongoDB, MySQL, and SQLite.

Install the Necessary Packages

You’ll need these dependencies:

bash
npm init -y
npm install express mongoose mysql2 sqlite3 cors dotenv
  • express for creating the backend API.
  • mongoose for MongoDB interaction.
  • mysql2 for MySQL interaction.
  • sqlite3 for SQLite interaction.
  • cors to handle cross-origin requests from the React frontend.
  • dotenv to manage environment variables.

2. Setting Up MongoDB Connection

MongoDB Setup

You need MongoDB running locally or you can use a cloud service like MongoDB Atlas.

javascript
// server.js (Backend for MongoDB)
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(express.json());

const mongoURI = process.env.MONGO_URI; // Example: 'mongodb://localhost:27017/mydb'

mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.error('MongoDB connection error:', err));

app.get('/data', (req, res) => {
// You can replace this with actual MongoDB model operations.
res.json({ message: 'Hello from MongoDB' });
});

app.listen(5000, () => {
console.log('Server is running on port 5000');
});

.env file for MongoDB

dotenv
MONGO_URI=mongodb://localhost:27017/mydb

3. Setting Up MySQL Connection

MySQL Setup

Install MySQL locally or use a cloud provider like Amazon RDS.

javascript
// server.js (Backend for MySQL)
const mysql = require('mysql2');

// Create MySQL connection
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'test_db',
});

db.connect(err => {
if (err) {
console.error('MySQL connection error:', err);
return;
}
console.log('MySQL connected');
});

app.get('/mysql', (req, res) => {
db.query('SELECT * FROM users', (err, results) => {
if (err) {
res.status(500).json({ error: 'Database error' });
} else {
res.json(results);
}
});
});

4. Setting Up SQLite Connection

SQLite Setup

SQLite is a serverless database. You only need to install the sqlite3 package.

javascript
// server.js (Backend for SQLite)
const sqlite3 = require('sqlite3').verbose();

// Create a new SQLite database (or open an existing one)
const db = new sqlite3.Database('./mydb.sqlite', (err) => {
if (err) {
console.error('SQLite connection error:', err);
return;
}
console.log('SQLite connected');
});

app.get('/sqlite', (req, res) => {
db.all('SELECT * FROM users', (err, rows) => {
if (err) {
res.status(500).json({ error: 'Database error' });
} else {
res.json(rows);
}
});
});

5. Connecting the React Frontend

Setting Up React to Fetch Data

In your React app, you can fetch data from the APIs that the backend exposes. For example:

bash
npx create-react-app frontend
cd frontend
npm start

Create a file called App.js in the src folder:

javascript
import React, { useEffect, useState } from 'react';

const App = () => {
const [data, setData] = useState(null);

useEffect(() => {
// Change this URL based on which database you want to interact with
fetch('http://localhost:5000/data') // MongoDB API endpoint
.then(response => response.json())
.then(data => setData(data.message));
}, []);

return (
<div>
<h1>{data ? data : 'Loading...'}</h1>
</div>

);
};

export default App;

6. Running the App

  1. Start your backend server:
    bash
    node server.js
  2. Start your React app:
    bash
    npm start
  3. Open your browser and go to http://localhost:3000 to see the React app displaying data from the backend.

Summary of Steps

  1. Backend Setup:
    • Install the necessary packages (express, mongoose, mysql2, sqlite3, cors, dotenv).
    • Set up the database connections (MongoDB, MySQL, SQLite) in the backend using Express.
    • Expose API routes to interact with the database.
  2. Frontend Setup:
    • Set up a React app.
    • Use fetch() to interact with the backend API.
  3. Run the Backend: Start the backend server (node server.js).
  4. Run the Frontend: Start the React app (npm start).

This is a simple tutorial on connecting React with MongoDB, MySQL, and SQLite via a backend. Depending on your use case, you may need to adjust the database queries, error handling, and API structure.

Related Posts

Leave a Reply