Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make redirect inside component in React router?

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}/>
like image 494
Alexandr Avatar asked Mar 07 '16 17:03

Alexandr


People also ask

How do I redirect on a react router?

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.

How do I redirect a component in a react function?

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.


1 Answers

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}`);
};
like image 136
Rick Runyon Avatar answered Sep 20 '22 19:09

Rick Runyon