Create your first React application with express and mongodb.

Rajat Sehgal
Jun 11 · 6 min read

Before we get directly into the tutorial i would like you to go through the usage of reactjs for which you can go through this blog — ReactJS -Why one should use it ?

Here in this tutorial you are gonna make a web application in which we will store info of Avengers in the mongodb database and crud apis will be handled by express framework as our backend server and frontend will be handled by ReactJs.


Architecture

Architecture of the react application

Setup database (Mongodb)

  • Install mongodb in your system and get into mongo shell by typing in terminal you will get into mongo shell.
mongo
  • Here execute command : —
show dbs

you will see no database named “avengers”.

  • Command to create database or to switch to database is
use avengers
  • Now you have database named “avengers”

Setup backend server (NodeJs server)

  • Enter into the main directory in which you will keep your backend file.
npm init
  • Running the above command will create package.json file which will help in order to add dependency packages to your server like mongodb, express or other functional.
  • Connection with mongodb database

You can keep the configuration of your react application at one place so that in future if you need to change some properties in your app then you just need to change it at one place, here we are using url variable from database.config file.

  • Set schema for data to be inserted into the database

We have named the schema as “nameSchema” for the two fields i.e. avenger and weapon so that only these two variables can get into the database no matter what other fields with them you try to insert.

mongoose.model(“weapons”,nameSchema) will make a model of namSchema and the data which you wanna insert will first map through the nameSchema and then get added into the “weapons” collection in “avengers” database. You can add more field according to your need.

  • API — insert

By this api you can insert the new avenger into the db. You need to send the object in request body.

  • API — showall

By this api you can fetch all the avengers present in your database.

When your node server is setup you can check the api through your browser.
  • API — delete

By this api you will be able to delete the particular avenger info from the db. You need to send the avenger name as title field in the request body.

  • API — update

By this api you can update the info of the avenger in the db.

And here when all this is complete your node server is ready.

Setup frontend (ReactJs)

This is what we gonna make, here our main moto is to setup the connection between a react app, node server and ofcourse database.

React enables to create components by invoking the React.createClass() (in ES6 createClass is replaced by Component) method which expects a render method.

class App extends Component { 

To create component classes we start with above line, before we were using React.createClass.

localhost:3001    //node server running on port 3001

Here super() function is used to intialize “this”, without super() we cannot use this in constructor.Main speciality of super() func is to inherit the properties from the parent class.

this.state = {data:[],open:false,name:'',weapon:''};

Whatever variable you wanna use inside your class or in its methods you have to declare them inside this.state.

fetch('http://localhost:3001/showall')
      .then(data => data.json())
      .then((data) => { 
        console.log(data);
        this.setState({ data: data }) });

When the object of this class is called then initially its constructor will be called and code inside the constructor will be executed. this.setState sets the variable which we have declared above in this.state. So, to use the existing data present inside mongodb we fetch the details by calling an api /showall and store the details inside the data variable.

this.handleChangeName = this.handleChangeName.bind(this);

Component instance where we can see event binding:

handleChangeName(event) {
    this.setState({
        name: event.target.value
    });
}handleChangeWeapon(event) {this.setState({
        weapon: event.target.value
    });
}

Component instance where no need of binding:

handleClickOpen = () => {
    this.setState({
        open: true
    });
};handleClose = () => {
    this.setState({
        open: false
    });
};

I have used Reacttable to create table in which getTdProps is the default function which is used to fetch the particular row info in the table. Both edit and delete function for particular avenger can be easily done with this getRowInfo function.

Update dialog box on click of edit button. Material-ui is used for dialogs.

updateEntry() is an arrow function which does not require binding and here it is to update the info of an avenger i.e. name and weapon fields. Api /update is called and the json with both updated fields is posted on this api by declaring the body field of the http request with obj.

This is the render function which renders the html code on the web page.

In the render function you can check the form attribute in which event is attached with the Submit button, on click which will trigger the onClickHandler() function.

onClickHandler() {
    console.log(this.refs['simpleForm'].getFormValues());
    let obj = this.refs['simpleForm'].getFormValues();
    fetch('http://localhost:3001/insert', {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(obj)
    });
}

onClickHandler function is gonna handle the form submition. To insert the info of an avenger in the database we will call an api /insert and post the input field values to it.

Now we have completed all stuffs according to our architecture discussed above. We have setup a node server running on port 3001 and we have connected our avengers mongodb database to it. From our react web application we are hitting apis insert, update, delete and showall on node server which atlast reflects the changes on our database.

You can check out and try to make something good from it. I hope you found this blog resourceful. Get the code here.

66

66 claps
Rajat Sehgal

Written by

Software developer at Lumiq.ai Noida, B.Tech from IIT Roorkee