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?
To redirect to another page on button click in React: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function, passing it the path - navigate('/about') . The navigate() function lets us navigate programmatically.
To open a page in a new tab on button click in React:When the button is clicked, use the window. open() method to load the resource. Set the target parameter to _blank when calling the open() method.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With