score:259
Actually it depends on your use case.
1) You want to protect your route from unauthorized users
If that is the case you can use the component called <Redirect />
and can implement the following logic:
import React from 'react'
import { Redirect } from 'react-router-dom'
const ProtectedComponent = () => {
if (authFails)
return <Redirect to='/login' />
}
return <div> My Protected Component </div>
}
Keep in mind that if you want <Redirect />
to work the way you expect, you should place it inside of your component's render method so that it should eventually be considered as a DOM element, otherwise it won't work.
2) You want to redirect after a certain action (let's say after creating an item)
In that case you can use history:
myFunction() {
addSomeStuff(data).then(() => {
this.props.history.push('/path')
}).catch((error) => {
console.log(error)
})
or
myFunction() {
addSomeStuff()
this.props.history.push('/path')
}
In order to have access to history, you can wrap your component with an HOC called withRouter
. When you wrap your component with it, it passes match
location
and history
props. For more detail please have a look at the official documentation for withRouter.
If your component is a child of a <Route />
component, i.e. if it is something like <Route path='/path' component={myComponent} />
, you don't have to wrap your component with withRouter
, because <Route />
passes match
, location
, and history
to its child.
3) Redirect after clicking some element
There are two options here. You can use history.push()
by passing it to an onClick
event:
<div onClick={this.props.history.push('/path')}> some stuff </div>
or you can use a <Link />
component:
<Link to='/path' > some stuff </Link>
I think the rule of thumb with this case is to try to use <Link />
first, I suppose especially because of performance.
score:1
One of the simplest way: use Link as follows:
import { Link } from 'react-router-dom';
<Link to={`your-path`} activeClassName="current">{your-link-name}</Link>
If we want to cover the whole div section as link:
<div>
<Card as={Link} to={'path-name'}>
....
card content here
....
</Card>
</div>
score:3
You also can Redirect
within the Route
as follows. This is for handle invalid routes.
<Route path='*' render={() =>
(
<Redirect to="/error"/>
)
}/>
score:15
Now with react-router v15.1
and onwards we can useHistory
hook, This is super simple and clear way. Here is a simple example from the source blog.
import { useHistory } from "react-router-dom";
function BackButton({ children }) {
let history = useHistory()
return (
<button type="button" onClick={() => history.goBack()}>
{children}
</button>
)
}
You can use this within any functional component and custom hooks. And yes this will not work with class components same as any other hook.
Learn more about this here https://reacttraining.com/blog/react-router-v5-1/#usehistory
score:25
You can also use react router dom library useHistory;
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
Source: stackoverflow.com
Related Query
- What is the best way to redirect a page using React Router?
- What is the best way to save my dynamicly created data using React and Javascript?
- what is the best way to use react router V6 navigation with redux and redux thunk actions?
- Redirect to a page that only show the contents of a component/page using React Router
- What is the best way to include css files for Prime React components when using Parceljs?
- What is the correct way to initiate a side-effect on page load when using React Strict Mode?
- What is the best way to render a search bar component that takes in a props in another component using react v6
- What is the best way to redirect to another page after successful action in Redux?
- What is the best way to pass in props to a react router route?
- What is the best way to architecture a React template using props children?
- What is the BEST way to do the error handling in react using Axios?
- What is the best way to access redux store outside a react component?
- What is the best way to trigger onchange event in react js
- What is the best way to deal with a fetch error in react redux?
- React - What is the best way to handle login and authentication?
- What is the correct way to animate/transition between routes in react router
- Reload the page gets 404 error using React Router
- What is the best way to secure Firebase API keys in a react app so it is not accessible publicly?
- What is the best way to implement undo state change (undo store/history implementation) in React Redux
- What is ACTUALLY the right way to transition/redirect using React Router?
- Using React Router to Redirect to next page after successful login
- What is the best way to do Error Handling in React Native App.
- What is the best way to update my react state when data in database changes?
- What is the best way to use a different API URL in production for a create-react-app using docker?
- React styled-component / e2e testing: What is the best way to use css selector?
- How to redirect to not found page if slug doesn't exist using React Router Dom?
- React - What is the Best Way to use Multiple createContexts?
- React Router Dom Redirect needs to refresh the page to work
- creating common header and sidebar across all the page using react router
- What is the simplest way to pass state while using React Router?
More Query from same tag
- viserjs Chart coming unwanted count number 01
- Display data from another array inside map function
- How to map array outside of render function to setState?
- Lazy load images, videos, and iframes in ReactJS rendered content
- how to redirect to "/" by using useHistory in React?
- how to test react-context using jest and enzyme where context is used inside constructor?
- Playing consecutive audio sounds in ReactJS. Delay issue when live
- react dispatch function after useSelector variable available
- Need to calculate on the parent the result of a hook call on each subcomponent
- Gatsby: How to change a node style if <Link /> is active?
- Fetch and setInterval react hooks problem
- Async/await in componentDidMount to load in correct order
- Fetch API Data in React
- Material UI: Grid does not put select in row
- Highlight part of Text
- Golang single page website server
- Enzyme/Mocha: How to test a react component function by firing an onChange event from a child component
- Google-maps-react doesn't work
- How to color an input box depending on the size of varible in ReactJs?
- React AntDesign add uploaded images to FormData
- Webpack2 - How to inline an SVG file
- How do I solve an error in my React Button Component?
- How to access JSON object key and value in ReactJS
- React component infinite update
- minmax CSS function is not recognized in React project
- Why does Axios get call return a 404 error with basic setup?
- React Router prevent random route
- How to use Jquery Plugin with React js and react-router-dom
- Can I add active class when url starts a string in react Navlink?
- Creating a multipart form component with Redux, Thunk, Axios