7

I am implementing a new app. Currently, I am able to do the navigation for the Link and couldn't do it for the button click navigation. I have checked this post and tried with BrowserHistory option. But this method is currently not supported.

Code:

import React, { Component } from "react";
import {Route,Router,NavLink,HashRouter,BrowserRouter} from "react-router-dom";
import Contact from "./components/Contact";
import Home from "./components/Home";
import EnquiryResult from "./components/EnquiryResult";
import logo from './logo.svg';
import './App.css';

class MainStack extends Component {

  onClick(){
   // browserHistory.push("/EnquiryResult");
}

  render() {
    return (
        <div>
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <div>
          <button className="btn" onClick={this.onClick.bind(this)}>Enquiry</button >
          </div>

          <ul className="header">
            <li><NavLink  to="/contact">Contact</NavLink ></li>
            <li><NavLink  to="/Home">Home</NavLink ></li>
          </ul>

          <div>
            <Route path="/Home" component={Home}/>
            <Route path="/contact" component={Contact}/>
            <Route path="/EnquiryResult" component={EnquiryResult}/>

        </div>
        </div>
    );
  }
}

export default MainStack;

navigation is working fine for the contact and Home. But couldn't achieve the navigation for the Enquiry. How can I achieve this button navigation?

halfer
  • 19,824
  • 17
  • 99
  • 186
Subburaj
  • 2,294
  • 3
  • 20
  • 37

5 Answers5

7

Using useHistory() from react-router-dom

import React from 'react';
import { useHistory } from "react-router-dom";
function NavigationDemo() {
  const history = useHistory();
  const navigateTo = () => history.push('/componentURL');//eg.history.push('/login');

  return (
   <div>
   <button onClick={navigateTo} type="button" />
   </div>
  );
}
export default NavigationDemo;
Maheshvirus
  • 6,749
  • 2
  • 38
  • 40
4

If your MainStack is wrapped in BrowserRouter you can use history like this:

onClick = () => this.props.history.push("/EnquiryResult");

And for the button:

<button className="btn" onClick={this.onClick}>Enquiry</button>
// No need to bind since we are using arrow function for our onClick.
devserkan
  • 16,870
  • 4
  • 31
  • 47
2

Correct way to navigate using context in react-router v4:

this.context.router.history.push('/EnquiryResult')

The new react-router v4 has changed the location of the push method when accessing this.context.router. router now has history and route as properties and it is within history that you will find the allocated method.

Also, if you are using the latest react version 15.5.0, propTypes have been removed into a separate package and you can get them with:

npm install prop-types --save

or

yarn add prop-types

Change the code like below

onClick(){
   this.context.router.history.push('/EnquiryResult')
}

Additionally, contextTypes needs to be declared as below

  static contextTypes = {
    router: PropTypes.object
  }
Subburaj
  • 2,294
  • 3
  • 20
  • 37
Prabhu
  • 1,057
  • 7
  • 13
  • 1
    I am getting an error as "Cannot read property 'history' of undefined". Which library needs to be imported? – Subburaj Jun 14 '18 at 07:07
  • can you install prop-types ? – Prabhu Jun 14 '18 at 07:14
  • I have already installed the prop-types. Now the navigation is working fine after importing (import PropTypes from "prop-types";) and declaring the contextTypes. – Subburaj Jun 14 '18 at 07:19
  • 1
    Thanks prabhu!!! Now it is working fine for me with contextTypes declaration. I have updated the answer with contextTypes declaration – Subburaj Jun 14 '18 at 08:55
  • @Subburaj Yes it's correct i forget to add contextTypes declaration thanks for your update – Prabhu Jun 14 '18 at 08:59
  • Good answer, just add the link to the docs, always link references to make a great one! – Marco Jan 05 '19 at 21:24
2

In react-router-dom v6 useHistory() function is replaced by useNavigate(). So using useHistory will lead you to this error:

Attempted import error: 'useHistory' is not exported from 'react-router-dom'

So just replace useHistory with useNavigate ex:

import { useNavigate } from 'react-router-dom'
export default function QuestionAnswer() {
    const navigate = useNavigate()
    return (
          <Button
                onClick={() => {
                  navigate(`/something`)
                }}
              >
                Click Me
          </Button>
    )
}

See more detail in this Attempted import error: 'useHistory' is not exported from 'react-router-dom' question

DINA TAKLIT
  • 7,074
  • 10
  • 69
  • 74
-1

You will need to import from react-router in order to get browserHistory work

import {browserHistory} from 'react-router';

Should work now

 onClick(){
   browserHistory.push("/EnquiryResult");
 }
Manoz
  • 6,507
  • 13
  • 68
  • 114