How to make redirect inside component in React router? I'm using react-rouer
import React from 'react'
import _ from 'lodash';
import FavoriteItem from '../components/FavoriteItem'
const FavoritesList = ({list}) => {
let transitionToItem = ({id}) => {
// make transition to `/details/${id}`
};
return (
<ul className="list-group favorites-list">
<FavoriteItem onFavoriteClick={ () => { transitionToItem(item); } } key={item.id} item={item}/>
</ul>
);
};
export default FavoritesList
Route:
<Route path="details/:item" name="details" component={DetailsPage}/>
The Redirect component was usually used in previous versions of the react-router-dom package to quickly do redirects by simply importing the component from react-router-dom and then making use of the component by providing the to prop, passing the page you desire to redirect to.
import { Redirect } from "react-router-dom"; The easiest way to use this method is by maintaining a redirect property inside the state of the component. Whenever you want to redirect to another path, you can simply change the state to re-render the component, thus rendering the <Redirect> component.
I think the preferred way to do this would be to wrap whatever element you're clicking on in a react-router Link
element and let the router handle everything.
<Link to=`/details/${item_id}`>Click me!</Link>
If you definitely want to take your approach, import the browserHistory
module from react-router into your component and push the new URL right onto it.
import { browserHistory } from 'react-router';
...
let transitionToItem = ({id}) => {
browserHistory.push(`/details/${id}`);
};
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