Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to connect to database in ReactJS

Introduction

Welcome to the world of programming, where lines of code can create beautiful interfaces, process data, and connect us with the world around us. One of the key aspects of modern web applications is interacting with databases. This vast topic can be intimidating for beginners, but don't worry, we're going to break it down together.

Today, we'll be focusing on how to connect to a database in ReactJS. ReactJS, or simply React, is a popular JavaScript library used for building user interfaces, particularly single-page applications. Think of it as a tool that helps you build the visual part of your application, the part users interact with. It's like the paint and brushes that artists use to create a masterpiece.

What is a Database?

Before we dive in, let's take a moment to understand what a database is. A database is a structured set of data. So, it's a place where you can store information, like user details, product information, or blog posts. Whenever you need this information, you can fetch it from your database. Think of it like a large, organized, digital filing cabinet.

Understanding the Basics of Connecting to a Database

Now, connecting to a database simply means establishing a communication link between your application (in our case, a React application) and a database. It's like dialing a phone number – you're setting up a line of communication between two points.

However, React being a client-side library, doesn't directly interact with databases. It communicates with an intermediary, usually a server-side language such as Node.js, which then interacts with the database. This intermediary is like a translator, helping your React app and your database understand each other.

Setting Up Your React Application

First, we need a React application. If you have one, great! If not, we can easily create one using Create React App, a tool that sets up a modern web app by running one command.

Here's how you can create a new application:

npx create-react-app react-database-connection

This command creates a new React application in a directory named react-database-connection. Feel free to replace react-database-connection with the name of your choice.

Creating a Server

As we mentioned earlier, React doesn't directly interact with databases, we need a server-side language to act as an intermediary. For this tutorial, we'll use Node.js with Express.js.

Express.js is a fast, unopinionated, minimalist web framework for Node.js. It provides a robust set of features for web and mobile applications.

To set up Express.js, navigate to your project directory and run the following commands:

cd react-database-connection
npm install express --save

This will install Express.js in your project. Now, let's create a new file called server.js in your project root directory and add the following code to it:

const express = require('express');
const app = express();
const port = 3001;

app.get('/', (req, res) => {
  res.send('Hello World!')
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`)
});

This is a simple Express server that listens on port 3001 and responds with "Hello World!" when you visit the root URL.

Connecting to a Database

For this example, we'll use MongoDB as our database. MongoDB is a source-available cross-platform document-oriented database program.

First, you need to install MongoDB in your project. You can do this by running the following command in your project directory:

npm install mongodb --save

Now, let's modify the server.js file to connect to MongoDB:

const express = require('express');
const mongodb = require('mongodb');
const app = express();
const port = 3001;

const MongoClient = mongodb.MongoClient;
const url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database connected!");
  db.close();
});

app.get('/', (req, res) => {
  res.send('Hello World!')
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`)
});

In this example, we're connecting to a MongoDB database located at mongodb://localhost:27017/mydb. Replace mydb with the name of your database.

Fetching Data from Database in React

Now that we've connected to our database, let's fetch some data from it and display it in our React app. To fetch data, we’ll use the built-in fetch function in JavaScript.

Let's create a new file, App.js, in your project directory, and add the following code to it:

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

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

  useEffect(() => {
    fetch('/api/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <h1 className="App-title">Welcome to React</h1>
      </header>
      <p className="App-intro">
        {data.map(item => (
          <div key={item.id}>{item.value}</div>
        ))}
      </p>
    </div>
  );
}

export default App;

In this code, we're fetching data from the /api/data endpoint and storing it in state using React's useState hook. We're then rendering this data in our component.

Conclusion

And there you have it! You now know how to connect a React application to a database. Of course, there's a lot more to learn about fetching, updating, and deleting data from a database, but this tutorial should give you a solid foundation to build upon.

Remember, practice makes perfect. The more you work with databases and React, the more comfortable you'll become. Happy coding!