Create React App with MongoDB - Part 3 Building the Frontend
Part 3: Building the frontend
The backend is ready, let’s build the frontend.
Understanding the frontend
So before we start writing code for the frontend part, we need to understand, what we are going to build. Our frontend part will contain a button. When clicked on this button, data the details collection will de display below it. We will display the name and age from every document of the collection.
Creating the react application.
Go to the directory that contains the backend folder. In the same directory, run the following command in a terminal.
1 | npx create-react-app frontend |
Here, “frontend” is the name of the folder that contains the default react project template and the dependencies are also installed with it. Go to this folder and type the following command to run the react application.
1 | npm start |
The browser will open and you will see something like this in it.
Adding bootstrap
Well, we are not building an application with many stylings, but still, we will use bootstrap in it. To install the bootstrap, use the following command.
1 | npm install bootstrap |
In the frontend folder, open the src folder. Then, open the App.js file. We need to import bootstrap here.
1 | import "bootstrap/dist/css/bootstrap.min.css"; |
Moreover, remove all the default code present in the App class.
Adding component
We will have one component in our application, that will contain the button. In the src folder, create a new directory and name it “components”. Go to this folder and create a new file. Name it “details”.
Add the following code in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import React, { Component } from "react"; export default class Details extends Component { render() { return ( <div className="container-fluid" style={{ marginTop: "30px" }}> <div className="row"> <div className="col-xs-12" style={{ textAlign: "center" }}> <button className="btn btn-primary" style={{ position: "absolute", marginLeft: "50%" }} > Click </button> </div> </div> </div> ); } } |
Now, open the app.js file and import this component in it. And then use this component in the App function. This is how the app.js file will look.
1 2 3 4 5 6 7 8 9 10 | import React from "react"; import "./App.css"; import "bootstrap/dist/css/bootstrap.min.css"; import Details from "./components/details"; function App() { return <Details />; } export default App; |
Conclusion
The button does nothing for the time being. The frontend part is complete. Next, we will connect the frontend with the backend and display data below the button.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started