When building modern web applications, React is one of the most popular choices for the frontend. But React alone cannot directly communicate with a database like MySQL because it’s just a frontend library (running on the client-side).
To connect React with MySQL, we need a backend server (for example, Node.js/Express, PHP, or Python). In this guide, we’ll use Node.js + Express as the backend and show you how React can interact with MySQL.
🔹 Step 1: Setup MySQL Database
First, create a database and table in MySQL:
CREATE DATABASE myapp;
USE myapp;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
🔹 Step 2: Build Backend with Node.js + Express
Create a new backend project:
mkdir backend
cd backend
npm init -y
npm install express mysql cors
Now create a file index.js:
const express = require("express");
const mysql = require("mysql");
const cors = require("cors");
const app = express();
app.use(cors());
app.use(express.json());
// MySQL connection
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "myapp",
});
db.connect(err => {
if (err) {
console.log("MySQL Connection Error:", err);
} else {
console.log("MySQL Connected!");
}
});
// Get all users
app.get("/users", (req, res) => {
db.query("SELECT * FROM users", (err, result) => {
if (err) return res.json({ error: err });
res.json(result);
});
});
// Insert user
app.post("/users", (req, res) => {
const { name, email } = req.body;
db.query("INSERT INTO users (name, email) VALUES (?, ?)", [name, email], (err, result) => {
if (err) return res.json({ error: err });
res.json({ message: "User added successfully" });
});
});
app.listen(5000, () => {
console.log("Server running on port 5000");
});
Run the backend:
node index.js
🔹 Step 3: Connect React with Backend
Now, let’s create a React app:
npx create-react-app frontend
cd frontend
npm install axios
In App.js:
import React, { useState, useEffect } from "react";
import axios from "axios";
function App() {
const [users, setUsers] = useState([]);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
useEffect(() => {
axios.get("http://localhost:5000/users")
.then(res => setUsers(res.data))
.catch(err => console.log(err));
}, []);
const addUser = () => {
axios.post("http://localhost:5000/users", { name, email })
.then(res => {
alert(res.data.message);
setUsers([...users, { name, email }]);
})
.catch(err => console.log(err));
};
return (
<div>
<h1>React + MySQL Example</h1>
<input type="text" placeholder="Name" onChange={e => setName(e.target.value)} />
<input type="text" placeholder="Email" onChange={e => setEmail(e.target.value)} />
<button onClick={addUser}>Add User</button>
<ul>
{users.map((user, i) => (
<li key={i}>{user.name} - {user.email}</li>
))}
</ul>
</div>
);
}
export default App;
✅ Conclusion
That’s it! 🎉 Now your React app can send and receive data from MySQL using a Node.js + Express backend.
Flow:
👉 React (frontend) → Node.js/Express (backend) → MySQL (database).
This setup is widely used in real-world applications and can be extended with authentication, validation, and advanced queries.
⚡ Pro Tip: You can also use PHP or Python instead of Node.js as the backend. The core idea is the same: React talks to the backend, and the backend talks to MySQL.
Top comments (0)