ExtraSun
ExtraSun

Reputation: 548

How to navigate from one component to another by clicking a button using React router

I want to use react-router-dom to navigate my website.
Every component will render <button> whenever onClick will active the switch to the next component.

Main component Login.js will contain all the 4 components inside it. I need to know what are the ways to do it.
(The first time user must not skip the login process below anyhow)

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

        class Login extends Component {
       render() {
        return (
          <div>
           <button  onClick={}></button>
          </div>
        );
      }
     }

Upvotes: 1

Views: 547

Answers (1)

Justin
Justin

Reputation: 86729

To redirect the user you want to call push on the history object. To get the history object in a class component you can use the withRouter higher-order component, e.g.

class Login extends Component {
  render() {
    const { history } = this.props;

    return (
      <div>
       <button onClick={() => history.push('foo')}>Login</button>
      </div>
    );
  }
}

export const LoginWithRouter = withRouter(Login);

Source: https://dev.to/kozakrisz/react-router---how-to-pass-history-object-to-a-component-3l0j

Upvotes: 1

Related Questions