Tuesday, 22 January 2019

How to implement Routing in ReactJS?

Implementing Routing in ReactJS.



Create a components folder in your react application and add below components into that folder.
rental.jsx
import React from "react";

const Rentals = () => {
  return <h1>Rentals Page</h1>;
};

export default Rentals;

movieForm.jsx
import React from "react";

const MovieForm = ({ match, history }) => {
  return (
    <div>
      <h1>Movie Form {match.params.id} </h1>
      <button
        className="btn btn-primary"
        onClick={() => history.push("/movies")}
      >
        Save
      </button>
    </div>
  );
};

export default MovieForm;

customer.jsx
import React from 'react';

const Cutomers = () => {
    return ( <h1>Customer Page</h1>  );
}

export default Cutomers;

loginForm.jsx
import React, { Component } from 'react';

class LoginForm extends Component {
    state = {  }
    handleSubmit = e => {
        // Call the server
        e.preventDefault();
        console.log("Submitted");
      };
    render() {
        return (
            <div>
                <div class="form-row">
                <form onSubmit={this.handleSubmit}>
                    <div className="form-group col-md-12">
                        <label htmlFor="inputEmail1">Email address</label>
                        <input type="email" className="form-control" id="inputEmail1" aria-describedby="emailHelp" placeholder="Enter email" />
                        <small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
                    </div>
                    <div className="form-group col-md-12">
                        <label htmlForfor="InputPassword1">Password</label>
                        <input type="password" className="form-control" id="InputPassword1" placeholder="Password" />
                    </div>
                    <div className="form-check">
                        <input type="checkbox" className="form-check-input" id="Check1" />
                        <label className="form-check-label" for="Check1">Check me out</label>
                    </div>
                    <button type="submit" className="btn btn-primary m-2">Submit</button>
                </form>
                </div>
            </div>
         );
    }
}

export default LoginForm;

notFound.jsx
import React from "react";

const NotFound = () => {
  return <h1>Page Not Found</h1>;
};

export default NotFound;


Add navbar.jsx file to the components folder and look into the below code.
import React from "react";
import { Link, NavLink } from "react-router-dom";

const NavBar = () => {
  return (
    <nav className="navbar navbar-expand-lg navbar-white bg-dark">
      <Link className="navbar-brand" to="/">
        Movies Library
      </Link>
      <button
        className="navbar-toggler"
        type="button"
        data-toggle="collapse"
        data-target="#navbarNavAltMarkup"
        aria-controls="navbarNavAltMarkup"
        aria-expanded="false"
        aria-label="Toggle navigation"
      >
        <span className="navbar-toggler-icon" />
      </button>
      <div className="collapse navbar-collapse" id="navbarNavAltMarkup">
        <div className="navbar-nav">
          <NavLink className="nav-item nav-link" to="/movies">
            Movies
          </NavLink>
          <NavLink className="nav-item nav-link" to="/customers">
            Customers
          </NavLink>
          <NavLink className="nav-item nav-link" to="/rentals">
            Rentals
          </NavLink>
          <NavLink className="nav-item nav-link" to="/loginForm">
            Log In
          </NavLink>
        </div>
      </div>
    </nav>
  );
};

export default NavBar;

Now modify the App.js file as below

import React, { Component } from 'react';
import './App.css';
import Movies from './components/movies';

import { Route, Redirect, Switch } from "react-router-dom";
import MovieForm from "./components/movieForm";
import Customers from "./components/customers";
import Rentals from "./components/rentals";
import NotFound from "./components/notFound";
import NavBar from "./components/navBar";
import LoginForm from './components/loginForm';

class App extends Component {
  render() {
    return (
      <React.Fragment>
      <NavBar />
      <main className="container">
        <Switch>
        <Route path="/loginForm" component={LoginForm} />
          <Route path="/movies/:id" component={MovieForm} />
          <Route path="/movies" component={Movies} />
          <Route path="/customers" component={Customers} />
          <Route path="/rentals" component={Rentals} />
          <Route path="/not-found" component={NotFound} />
          <Redirect from="/" exact to="/movies" />
          <Redirect to="/not-found" />
        </Switch>
      </main>
    </React.Fragment>
    );
  }
}

export default App;

Modify the Index.js file as below

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.css';
import 'font-awesome/css/font-awesome.css';
import {BrowserRouter} from 'react-router-dom';

ReactDOM.render(<BrowserRouter><App /></BrowserRouter>, document.getElementById('root'));

serviceWorker.unregister();

If you are facing any issues while running the application try to install respective npm packages. It will resolve the compilation errors and run the application smoothly.


2 comments: