Ad
Redirect On Button Click In React
Can anyone please tell me how redirect works in react?
I'm from Angular background and trying to learn React.
I have a small application, where I want to redirect the user to profile
component on click of a button.
This is a very basic requirement but there's no proper documentation available (or I'm not able to find one).
Any help will be appreciated.
Here's my code:
import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";
<BrowserRouter>
<Switch>
<Route path="/" exact render={props => <Index {...props} />} />
<Route path="/login-page" exact render={props => <Login {...props} />} />
<Route path="/profile-page" exact render={props => <Profile {...props} />} />
<Route path="/dashboard" exact render={props => <Dashboard {...props} />} />
<Redirect to="/" />
</Switch>
</BrowserRouter>,
<Button color='primary' onClick={e => this.viewProfile()}>View Profile</Button>
viewProfile = function () {
console.log("clicked");
}
Ad
Answer
React Router comes with a Link
component that can be used for this. Just import it, set the destination in the to
prop, and wrap your Button
with it:
import { Link } from "react-router-dom";
<Link to='/profile-page'>
<Button color='primary' onClick={e => this.viewProfile()}>View Profile</Button>
</Link>
viewProfile = function () {
console.log("clicked");
}
Have a look at the React Router docs, they've got a lot of useful info!
Ad
source: stackoverflow.com
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad