Full stack with React / MERN Stack Development

Posted on July 31, 2019
expressjs
axios
mongodb
reactjs
Router
1058

This article will be helpful for those who want to try out the complete stack development in javascript. I am using react as frontend, MongoDB as Database, react-router-dom for rest-api calls.

If you have Node and MongoDB installed in your machine just skip the installation part and start building the application.

Installation: 

While installing check add path (It will allow you to work with command prompt directly.) options

Node : Download from here

MongoDB: Download from here

Start:

open command prompt 

npx create-react-app koderplace-app

Difference between npx and npm??

npx is a package runner, the way it designed is that we can directly use the packages from npm registry without even installing it into your application.Earlier we were doing it with the help of npm (Install to our location and using it.)

By this stage we have creaed the application folder called koderplace-app.We will start writing one form helps the user/ admin to register and login.

Used react-bootstrap as ui framework to work with the application, 

npm install react-bootstrap 

Used react-router-dom for the routes navigation

npm install react-router-dom

Create a folder called components under src. You suppose to create one Home Componennt and one Admin Component.

src/components/Home.js (A simple component only one division for text display)

import React from 'react';
export default class Home extends React.Component{
  render(){
    return(
      <div>Home Page</div>
    );
  }
}

src/components/AdminDialog.js (Drag down to that specific link)

A huge Component included lot of things. I am using semantic-ui-react instead of react-bootstrap just to give you a perception on how to use it ?

I am using axios to get the data from server.We have not yet started the backened code. we will write the code first for backened and get back here and work.So to work with mongodb, we will create one folder called backened under src.

create a model called login.model.js under src/backened. we are expecting only userName and email (No validations as of now).

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Login = new Schema({
    UserName: {
        type: String
    },
    Email: {
      type: String
    },
});
module.exports = mongoose.model('Login', Login);

create a file called server.js under src/backened.

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const koderRoutes = express.Router();
const PORT = 4000;
let Login = require('./login.model');
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://127.0.0.1:27017/koderplace', { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
    console.log("MongoDB database connection established successfully");
})

koderRoutes.route('/').get(function(req, res) {
    Login.find(function(err, todos) {
        if (err) {
            console.log(err);
        } else {
            res.json(todos);
        }
    });
});


koderRoutes.route('/login/:id').get(function(req, res) {
    var newLogin = {UserName: req.params.id};
    Login.find(newLogin, function(err, todo) {
        if (!todo)
            res.status(404).send("data is not found");
        else
            res.json(todo);
    });
});

koderRoutes.route('/login').post(function(req, res) {
    let createEntry = new Login(req.body);
    createEntry.save()
        .then(todo => {
            res.status(200).json({'user': 'user added successfully to the database'});
        })
        .catch(err => {
            res.status(400).send('Registration failed. Try again');
        });
});

app.use('/koderplace', koderRoutes);
app.listen(PORT, function() {
    console.log("Server is running on Port: " + PORT);
});

 

Here the database name is koderplace and collection is logins.You can create database by MongoDBCompassCommunity or by command prompt.

By MongoDBCompassCommunity

By Command Line 

    

Start server : Go to the path(src/backened) and try nodemon server.js

Initialize mongo: By typing mongod(If the mongod is not added to path,Go to the specific folder where you have installed MongoDB & try from there Ex: C:\Program Files\MongoDB\Server\4.0\bin).

If the mongo is not intialized try to create a folder data under C drive & db under data.Try intializing mongod now.

Ex: C:\data\db

import React from 'react';
import { Container, Button, Form} from 'semantic-ui-react';
import axios from 'axios';

export default class AdminDialog extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      UserName: 'Koder1',
      Email: 'koderplace@google.com',
      logging: 'login',
      successfulLogin: false,
    };
    this.onSubmit = this.onSubmit.bind(this);
    this.onUserNameChange = this.onUserNameChange.bind(this);
    this.onEmailChange = this.onEmailChange.bind(this);
    this.onLoginOptionChange = this.onLoginOptionChange.bind(this);
    this.loadComponent = this.loadComponent.bind(this);
    this.EntryForm = this.EntryForm.bind(this);
    this.loginForm = this.loginForm.bind(this);
  }


  onLoginOptionChange(e, {value}) {
    this.setState({
      logging: value,
    });
  }



  onSubmit(e) {
    e.preventDefault();
    if(this.state.logging === "login") {
      let userCredentials = {UserName: this.state.UserName};
      axios.get('http://localhost:4000/strand/login/'+this.state.UserName, userCredentials)
          .then(res => {
            console.log(res.data);
            console.log('login successful');
            this.setState({
              successfulLogin: true
            });
          })
          .catch(function (error){
              console.log(error);
          });
    }else {
      let userCredentials = {UserName: this.state.UserName, Email: this.state.Email};
      axios.post('http://localhost:4000/strand/login', userCredentials)
          .then(res => console.log(res.data));
          this.setState({
            UserName: '',
            Email: '',
            successfulLogin: true
          });
          console.log('Registered successfully');
    }
  }

  onEmailChange(e) {
      this.setState({
        Email: e.target.value,
      });
  }

  onUserNameChange(e) {
    this.setState({
      UserName: e.target.value,
    });
  }

  loginForm() {
      return(<Form>
        <Form.Group inline>
          <Form.Radio
            label='Login'
            value='login'
            checked={this.state.logging === 'login'}
            onChange={this.onLoginOptionChange}
          />
          <Form.Radio
            label='Register'
            value='register'
            checked={this.state.logging === 'register'}
            onChange={this.onLoginOptionChange}
          />
          </Form.Group>

      {this.state.logging === 'login' ? <div />:<Form.Field>
        <input type="email" value={this.state.Email} onChange={this.onEmailChange} placeholder="Email" />
      </Form.Field>}

        <Form.Field>
          <input type="text" value={this.state.UserName} onChange={this.onUserNameChange} placeholder="UserName" />
        </Form.Field>
        <Button type="submit" onClick={this.onSubmit}>
          Submit
        </Button>
      </Form>);
  }


  EntryForm(){
    return (   <div> Logged In</div>  );
  }

  loadComponent(){
    return (this.state.successfulLogin? this.EntryForm(): this.loginForm());
  }

  render(){
    return(
      <Container style={{marginTop:'10px' }} >
        {this.loadComponent()}
      </Container>
    );
  }
}

Try to remove everything in App.js try to write the below code.

import React, { Component } from 'react';
import "bootstrap/dist/css/bootstrap.min.css";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import { Navbar, Nav, Form, FormControl, Image } from 'react-bootstrap';
import AdminDialog from './components/AdminDialog';
import Home from './components/Home';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {item:''};
    this.loadComponent = this.loadComponent.bind(this);
    this.selected = this.selected.bind(this);
  }

  selected(e) {
    this.setState({
      item: e.target.id,
    });
  }

  loadComponent() {
    if(this.state.item === 'admin')
      return <Route path="/login" exact component={AdminDialog} />;
    return <Home />
  }

  render() {
    return (
      <Router>
        <Navbar bg="light" expand="lg">
          <Navbar.Brand href="#home"><Image src="./resources/logo.png" width="40" height="50" /></Navbar.Brand>
            <Navbar.Collapse id="basic-navbar-nav">
              <Nav className="mr-auto">
                <Nav.Link href="#link"><Link id="admin" onClick={this.selected} to="/login">Admin</Link></Nav.Link>
              </Nav>
              <Form inline>
                <FormControl type="text" placeholder="Search" className="mr-sm-2" />
              </Form>
          </Navbar.Collapse>
        </Navbar>
        {this.loadComponent()}
      </Router>
    );
  }
}

export default App;

 




0 comments

Please log in to leave a comment.