3
votes

Trying on simple navigation with react-router-dom. Managed to have it works with this.props.history.push('/pathName'); However, I have doubts about my understanding and implementation, appreciate your 2 cents on correcting my mistakes.

Am I in the right direction?

My use case scenario:

Firstly, I have 3 pages with a common component <Navbar> implemented on top of each page. Navbar consists of 2 buttons Page A and Page B. User should be navigated to either screen when the respective button is clicked.

  1. Homepage
  2. Page A
  3. Page B

My Implementation:

Homepage.js - (Besides the class name is different, both Page A and B has the same implementation)

import React from 'react';
import { Redirect } from "react-router-dom";

import Navbar from '../common/navbar';

class Homepage extends React.Component{  

 callBackFromNavBar = (value) => {
    NavigationHelper.historyPush(this.props, value);
  }

  render(){

    return (
      <div>
          <Navbar callback={this.callBackFromNavBar}/>
      </div>
    );
  }
}

export default Homepage;

NavigationHelper.js

export const historyPush = (props,value) => {
    console.log('helper calling');
    switch(value){
        case 'PageA':
            props.history.push('/PageA');
            break;
        case 'PageB':
            props.history.push('/PageB');
            break;
        default:
            break;
    }
}

Navbar - Following shows how the value is being pass back to parent

<Button variant="contained" onClick={ () => {
            props.callback('PageA');
          } }>Page A</Button>

Learning source:

  1. https://dev.to/projectescape/programmatic-navigation-in-react-3p1l

Link to Sandbox

https://codesandbox.io/embed/react-router-dom-navigation-4tpzs?fontsize=14&hidenavigation=1&theme=dark

1
can you share codesandbox linkvinayak shahdeo
tried doing it on codesandbox, didnt manage to make it work. Maybe you can point out which part is unclear to you?TommyLeong
@vinayakshahdeo I have updated the question with Sandbox link.TommyLeong

1 Answers

0
votes

I would try something like this to simplify things

import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import PageA from './'
import PageB from './'

function App() {
  return (
   <Router>
     <Navbar />
        <Switch>
          <Route exact path="/" component={Home} />
          <Route exact path="/pageA" component={PageA} />
          <Route exact path="/pageB" component={PageB} />
        </Switch>
    </Router>
  );
}

And then in your Navbar component just setup the <Link> to each of those pages, here i have setup the routes in the App.js file however i have seen people just use a dedicated component for routing but find what works best for you