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?

2
  • Is your MainStack wrapped in BrowserRouter or not? Commented Jun 14, 2018 at 7:20
  • yeah. MainStack is wrapped with BrowserRouter . Commented Jun 14, 2018 at 7:25

5 Answers 5

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;
Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

I am getting an error as "Cannot read property 'push' of undefined"
What do you see when you console.log(this.props)? By the way, a simple working example: codesandbox.io/s/5mv52vy374
Now I have changed my index.js file as per your example and it is working fine for me.
LINK IS NOT WORKING, PLEASE TELL ME HOW TO FIX THIS "cannot read property 'push' ERROR?
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
  }

6 Comments

I am getting an error as "Cannot read property 'history' of undefined". Which library needs to be imported?
can you install prop-types ?
I have already installed the prop-types. Now the navigation is working fine after importing (import PropTypes from "prop-types";) and declaring the contextTypes.
Thanks prabhu!!! Now it is working fine for me with contextTypes declaration. I have updated the answer with contextTypes declaration
@Subburaj Yes it's correct i forget to add contextTypes declaration thanks for your update
|
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

Comments

-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");
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.