DEV Community

Sunny
Sunny

Posted on

How to navigate and switch components with BrowserRouter

I want to switch between components after the user entered the requested info.

Components that will be shown to user by this order:

  1. {MobileNum } Enter mobile number
  2. {IdNumber } ID number
  3. {CreatePassword } Create Password

When all these steps are completed the browser will switch to the home page.
The first time user must not be able to move between pages until he filled each request.

Without using *React Router* I used to switch only two components with a conditional rendering

Now I definitely want a better way with BrowserRouter as if I had 3-4 components inside Login.

import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Redirect,
  Route,
  Switch,
} from 'react-router-dom';
import MobileNum from './MobileNum.jsx';
import IdentNumber from './IdNum.jsx';
import CreatePassword from './createPassword .jsx';

class Login extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <Router>
          <Switch>
            <Route path='/'  component={MobileNum} />                                                
            <Route path='/'  component={IdNum} />
            <Route path='/'  component={CreatePassword } />
          </Switch>
        </Router>
      </div>
    );
  }
}

export default Login;
Enter fullscreen mode Exit fullscreen mode

I searched the web in reactrouter.com and many others as here for a clean solution but found no answer.

Any Idea what's the best way to do it ?

Thanks

Discussion (0)