Search code examples
javascriptreactjsreact-reduxreact-router

How to handle the navigation for the Button click in ReactJS?


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?


Solution

  • 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.