How to Connect a React App with MongoDB: A Complete Guide

Ashish prajapati - Oct 21 - - Dev Community

In modern web development, building full-stack applications often involves connecting a front-end framework like React with a database to store and manage data. MongoDB, a popular NoSQL database, pairs well with React for building scalable and flexible web apps. However, since React is a client-side framework, it can't directly interact with a database. That's where a back-end server—typically built with Node.js and Express—comes in.

In this article, we’ll explore the steps needed to connect a React app with MongoDB through an Express API. By the end of this guide, you’ll understand the process of setting up both the front-end and back-end for a full-stack React and MongoDB application.

1. Setting up the Back-end with Node.js and Express

To connect React with MongoDB, we need to establish a server that can interact with the database. Node.js is commonly used to set up this server, and Express.js, a minimalist web framework, makes it easy to create RESTful APIs that your React app can communicate with.

Step 1.1: Install Node.js and Set Up the Project

To get started, install Node.js from here. After installation, create a new directory for your project and initialize a Node.js app:

mkdir react-mongo-app
cd react-mongo-app
npm init -y
Enter fullscreen mode Exit fullscreen mode

This initializes a basic Node.js project. Next, install Express to handle HTTP requests:

npm install express
Enter fullscreen mode Exit fullscreen mode

Step 1.2: Set Up an Express Server

In the root of your project, create a file called server.js to define your server:

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const PORT = 5000;

// Middleware
app.use(cors());
app.use(express.json());

// MongoDB Connection
mongoose.connect('mongodb://localhost:27017/mydatabase', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});

const db = mongoose.connection;
db.on('error', (error) => console.error(error));
db.once('open', () => console.log('Connected to MongoDB'));

// Routes
app.get('/', (req, res) => {
    res.send('Hello from Express');
});

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Here, we’re setting up a basic Express server that connects to a MongoDB database running locally. If you don’t have MongoDB installed, you can either install it locally or use MongoDB Atlas, a cloud-hosted version of MongoDB.

Step 1.3: Install Mongoose and MongoDB

MongoDB requires a way to interact with your Express server. Mongoose, an Object Data Modeling (ODM) library, makes it easy to define schemas and interact with MongoDB. Install Mongoose with the following command:

npm install mongoose
Enter fullscreen mode Exit fullscreen mode

Make sure MongoDB is running by either starting it locally with mongod or by setting up a cloud instance with MongoDB Atlas.

Step 1.4: Define a Mongoose Model

Mongoose allows you to define schemas that represent the structure of the data you’ll store in MongoDB. For example, let’s create a schema for a simple item with a name and price:

const mongoose = require('mongoose');

const itemSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    price: {
        type: Number,
        required: true,
    }
});

module.exports = mongoose.model('Item', itemSchema);
Enter fullscreen mode Exit fullscreen mode

This Item model defines how data will be stored in MongoDB, with each item having a name and a price.

Step 1.5: Create API Routes

Now, let’s set up the API routes to handle requests from the React app. Add the following routes to your server.js to enable basic CRUD operations:

const Item = require('./models/Item');

// Create Item
app.post('/items', async (req, res) => {
    const item = new Item({
        name: req.body.name,
        price: req.body.price,
    });

    try {
        const newItem = await item.save();
        res.status(201).json(newItem);
    } catch (err) {
        res.status(400).json({ message: err.message });
    }
});

// Get all Items
app.get('/items', async (req, res) => {
    try {
        const items = await Item.find();
        res.json(items);
    } catch (err) {
        res.status(500).json({ message: err.message });
    }
});
Enter fullscreen mode Exit fullscreen mode

These routes allow you to create new items and fetch all items from MongoDB. The React front-end will interact with these routes to manage data.

2. Setting up the Front-end with React

Now that the back-end is ready, we’ll move to the front-end, which is where React comes in. The React app will communicate with the back-end API to display data and handle user inputs.

Step 2.1: Create a React App

First, create a new React app using the create-react-app command:

npx create-react-app react-mongo-client
cd react-mongo-client
Enter fullscreen mode Exit fullscreen mode

Step 2.2: Install Axios for API Calls

Axios is a promise-based HTTP client that simplifies making requests to the back-end. Install Axios in your React project:

npm install axios
Enter fullscreen mode Exit fullscreen mode

Step 2.3: Fetch Data from the Express API

In your App.js, use Axios to fetch data from your Express server. Here’s an example of how to get all items from the /items route we set up earlier:

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

function App() {
    const [items, setItems] = useState([]);

    useEffect(() => {
        axios.get('http://localhost:5000/items')
            .then((response) => {
                setItems(response.data);
            })
            .catch((error) => {
                console.error('There was an error fetching the items!', error);
            });
    }, []);

    return (
        <div className="App">
            <h1>Items</h1>
            <ul>
                {items.map((item) => (
                    <li key={item._id}>{item.name}: ${item.price}</li>
                ))}
            </ul>
        </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

This code sends a GET request to the back-end API and displays the items retrieved from MongoDB.

3. Running the Full-Stack Application

Once both the back-end and front-end are set up, you can run the app:

Step 3.1: Start the Express Server

In the back-end folder, run the Express server:

node server.js
Enter fullscreen mode Exit fullscreen mode

Step 3.2: Start the React App

In the React app folder, start the development server:

npm start
Enter fullscreen mode Exit fullscreen mode

At this point, your React app should be able to communicate with the Express API and MongoDB, displaying data retrieved from the database.

4. Deploying the App

To deploy this full-stack app, you can use platforms like Netlify or Vercel for the React front-end and services like Heroku or AWS for the back-end. MongoDB Atlas can handle the database in the cloud, allowing for scalability and easy management.

Conclusion

Connecting a React app with MongoDB requires a back-end server to handle database operations. In this guide, we walked through setting up a Node.js and Express back-end, connecting it to MongoDB via Mongoose, and building a React front-end to interact with the data. With this architecture, you can build powerful full-stack applications that scale and adapt to various use cases.

. . . . . . . . . . . . . . . . . . . . . . . .