DEV Community

Cover image for How To Connect React JS with MongoDB
Udemezue John
Udemezue John

Posted on

How To Connect React JS with MongoDB

Introduction.

Connecting React.js with MongoDB is a crucial step in building modern, full-stack applications. React, known for its efficient, component-based UI architecture, often relies on a powerful backend to store and retrieve data in real time.

That's where MongoDB comes in—a NoSQL database that's not only flexible but also scalable enough to handle a wide variety of data structures.

In this post, I’ll guide you through the process of connecting a React frontend to a MongoDB database, covering everything from setting up a Node.js/Express server to managing data transfers between the client and the database.

The aim here is to provide a straightforward approach that can help you build and deploy applications with dynamic, real-world data.

Why MongoDB?

Why MongoDB? For one, it's document-oriented, meaning it handles JSON-like data natively, which fits perfectly with the structure of data that React components typically deal with.

Moreover, its scalability and ease of use have made MongoDB one of the most popular databases for web applications.

MongoDB's 2023 market share was estimated at 5.16% among databases globally, with over 75 million downloads from developers seeking fast, flexible database solutions.

By the end of this tutorial, you'll have a functional application where React serves as the frontend, Express.js powers the backend, and MongoDB stores all your persistent data

How Do I Connect React JS with MongoDB?

Connecting React.js with MongoDB is an essential skill for building modern web applications.

In this blog post, I’ll guide you through the process of setting up a React application and connecting it to a MongoDB database, ensuring you can seamlessly manage your data.

Prerequisites

Before diving in, make sure you have the following set up on your machine:

  • Node.js: Ensure you have Node.js installed. You can download it from Node.js Official Site.
  • MongoDB: If you want to run MongoDB locally, you can download it from MongoDB Official Site. Alternatively, consider using a cloud-based solution like MongoDB Atlas.
  • Basic understanding of JavaScript and React: Familiarity with JavaScript and React will make this process smoother.

Step 1: Set Up Your React Application.

To start, I’ll create a new React application using Create React App, which sets up everything I need for a React application with just one command. Open your terminal and run:

npx create-react-app my-app
cd my-app
Enter fullscreen mode Exit fullscreen mode

This command creates a new folder called my-app, installs all necessary dependencies, and sets up a basic React application structure.

Step 2: Set Up a Backend Server

Since React is a front-end library, I need a backend to connect to MongoDB. I’ll use Express.js for this purpose. To set it up, I can create a new folder within my project directory.

Create a new folder called server:

mkdir server
cd server
Enter fullscreen mode Exit fullscreen mode

1.Initialize a new Node.js application:

npm init -y
Enter fullscreen mode Exit fullscreen mode

2.Install the necessary dependencies:

npm install express mongoose cors dotenv
Enter fullscreen mode Exit fullscreen mode
  • express: A web application framework for Node.js.
  • mongoose: An ODM (Object Data Modeling) library for MongoDB and Node.js.
  • cors: Middleware for enabling CORS (Cross-Origin Resource Sharing).
  • dotenv: For loading environment variables.

Step 3: Configure the Server.

Next, I’ll create a basic Express server. In the server folder, create an index.js file:

// server/index.js

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 5000;

// Middleware

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

//MongoDB connection

mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log("MongoDB connected"))
    .catch(err => console.error(err));

//Start the server

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


Enter fullscreen mode Exit fullscreen mode
  • In this code snippet: I set up a basic Express server and added middleware for CORS and JSON parsing.
  • I also connected to MongoDB using Mongoose. For this, I need to create a .env file in the server folder to store my MongoDB connection string.

Step 4: Create the .env File.

Create a .env file in the server directory and add the following line:

MONGO_URI=mongodb://<username>:<password>@localhost:27017/mydatabase
Enter fullscreen mode Exit fullscreen mode

Replace , , and mydatabase with your actual MongoDB credentials and database name. If you’re using MongoDB Atlas, you’ll find the connection string in your cluster dashboard.

Step 5: Create a Model.

Now, I’ll create a model for the data I want to store in MongoDB. Inside the server folder, create a folder named models, and then create a file named Item.js:

// server/models/Item.js

const mongoose = require('mongoose');

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

module.exports = mongoose.model('Item', itemSchema);
This schema defines an item with a name and quantity.
Enter fullscreen mode Exit fullscreen mode

Step 6: Set Up Routes.

I need to create routes to handle CRUD (Create, Read, Update, Delete) operations.

Inside the server folder, create a folder named routes, and then create a file named itemRoutes.js:

// server/routes/itemRoutes.js

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

const router = express.Router();

// Create Item
router.post('/', async (req, res) => {
    const newItem = new Item(req.body);
    try {
        const savedItem = await newItem.save();
        res.status(200).json(savedItem);
    } catch (err) {
        res.status(500).json(err);
    }
});

// Get All Items
router.get('/', async (req, res) => {
    try {
        const items = await Item.find();
        res.status(200).json(items);
    } catch (err) {
        res.status(500).json(err);
    }
});

// Export routes

module.exports = router;

Enter fullscreen mode Exit fullscreen mode

Step 7: Integrate Routes into the Server.

Now I’ll integrate these routes into my main server file. Update index.js to include:

// server/index.js

const itemRoutes = require('./routes/itemRoutes');

// Existing code...

app.use('/api/items', itemRoutes);

Enter fullscreen mode Exit fullscreen mode

Step 8: Start the Server.

Now that everything is set up, I’ll start the backend server. In the terminal, run:

node index.js
Enter fullscreen mode Exit fullscreen mode

If everything is configured correctly, I should see "MongoDB connected" and "Server is running on port 5000" in the console.

Step 9: Set Up React to Connect to the API.

Now it’s time to connect my React front-end to the Express backend. In the my-app folder, I’ll install Axios to make HTTP requests:

npm install axios
Enter fullscreen mode Exit fullscreen mode

Step 10: Create a Component to Fetch Data.

Inside the src folder of my React app, I’ll create a new component called ItemList.js:

// src/ItemList.js

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

const ItemList = () => {
    const [items, setItems] = useState([]);

    useEffect(() => {
        const fetchItems = async () => {
            const res = await axios.get('http://localhost:5000/api/items');
            setItems(res.data);
        };
        fetchItems();
    }, []);

    return (
        <div>
            <h1>Item List</h1>
            <ul>
                {items.map(item => (
                    <li key={item._id}>{item.name}: {item.quantity}</li>
                ))}
            </ul>
        </div>
    );
};

export default ItemList;

Enter fullscreen mode Exit fullscreen mode

Step 11: Use the Component in Your App.

Finally, I’ll render the ItemList component in the App.js file:

// src/App.js

import React from 'react';
import ItemList from './ItemList';

function App() {
    return (
        <div className="App">
            <ItemList />
        </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 12: Run the React Application.

Now, I’ll start the React application. In a new terminal window, navigate to the my-app folder and run:

npm start
Enter fullscreen mode Exit fullscreen mode

If everything has been set up correctly, you should see the item list rendered in your browser.

You can now interact with your React application, which connects to your MongoDB database via the Express backend.

Conclusion.

Connecting React.js with MongoDB might seem daunting at first, but breaking it down into these manageable steps makes the process easier.

With the backend set up using Express and Mongoose, and the frontend created with React, you now have a fully functioning web application capable of managing data.

If you want to expand further, consider implementing CRUD operations to allow adding, updating, and deleting items.

This project can serve as a solid foundation for more complex applications, so don’t hesitate to build upon it!

Top comments (0)