Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to navigate on path by button click in react router v4?

I have this paths in react-router-dom:

 <BrowserRouter>   <div>   <Route exact path='/(index.html)?' component={Home}/> {/* app = home */}   <Route  path='/register' component={Registration}/>   </div> </BrowserRouter> 

everything is working fine, now anywhere in my components I want to change path by onClick, a code like this:

<button onClick={() => history.push('/the/path') }> change path </button> 

how can I do that?

like image 626
gpbaculio Avatar asked Jul 03 '17 04:07

gpbaculio


People also ask

How do you route on click of button in react?

To navigate to the courses route, we will use the history. push method of the useHistory object. We will add an event handler “onClick” for our button component and define a function “coursesPage ” that handles the click event. The coursesPage function enables us to redirect to another route on clicking the button.

How do you programmatically navigate using react router v4?

There are two ways to programmatically navigate with React Router - <Navigate /> and navigate() . You can get access to Navigate by importing it from the react-router-dom package and you can get access to navigate by using the custom useNavigate Hook.

How do you navigate on path by button click in react v6 router?

To redirect page on click of a button with React Router v6, we use the useNavigate hook. to call the useNavigate hook to return the navigate function. Then we call navigate with path to navigate to the path in the routeChange function.

Which router hook should you use to change the route path on a button click?

useNavigate hook The first argument is required and determine where you want to go. It can be a route or a number. For example, navigate('/some-route'), navigate(-1) (go back), etc.


2 Answers

import {withRouter} from 'react-router-dom'; ...  class App extends React.Component {   ...    nextPath(path) {     this.props.history.push(path);   }    render() {     return (       <button onClick={() => this.nextPath('/the/path') }>         change path        </button>     );   } }  export default withRouter(App); 
like image 152
soywod Avatar answered Sep 20 '22 14:09

soywod


If you're using the button only for navigation, you can replace it with <Link />1 and apply a button style.

<Link to='/new/location/'>Click Me</Link> 

Or you can use the <NavLink />2.

In case of using Material UI, you can use the following code:

import { Link } from 'react-router-dom' import Button from '@material-ui/core/Button';  <Button component={Link} to="/new/location/">   Click Me </Button> 

(1): import {Link} from "react-router-dom";
(2): import {NavLink} from "react-router-dom";

like image 34
frogatto Avatar answered Sep 21 '22 14:09

frogatto