MongoDB with ReactJS

Connect MongoDB with ReactJS ?

First, we create a react app, and then for backend maintenance, we create API in node.js and express.js which is running at a different port and our react app running at a different port. for connecting React to the database (MongoDB) we integrate through API. Now see how we create a simple React app that takes the input name and email from users and saved it to the database.

Prerequisite:

  • NodeJS installed in your system (install)
  • MongoDB installed in your system (install)

Setting up the required files and folders for the frontend and backend both one by one.

  • Create React App: To build a react application follow the below steps:

Step 1: Create a react application using the following command

npx create-react-app foldername

Step 2: Once it is done change your directory to the newly created application using the following command

cd foldername

Step to run the application: Enter the following command to run the application.

npm start

Backend Setup With NodeJS: Setup NodeJs for Backend to integrate with frontend.

Step1: Make a folder in the root directory using the following command

mkdir backend

Step 2: Once it is done change your directory to the newly created folder called backend using the following command

cd backend

Step 3: Run the following command to create configure file

npm init -y

Step 3: Now Install the mongoose MongoDB using the following command.

npm i express mongoose mongodb cors

Step 4: Create a file that is index.js

touch index.js

Project Structure: It will look like the following:

Project Structure

 

Step to run the application: Enter the following command to run the application.

nodemon index.js

Example: Now write down the following code in the following files:

index.js
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

sixteen − 12 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top