Passing data using state in Link tag in React router

Viewed 10592

I don't know where I'm wrong. I want to pass that parameter as a state to Link tag and get that in another component.

import React from 'react'
import {Link} from "react-router-dom";

export default class CategoryList extends React.Component{


    render(){
        return(
            <tr>
                <td>
                    <Link to={{pathname:"/Topics/" + this.props.row.Occupation+"/"+this.props.row.objectId +'/id'+'/'+this.props.userName, state:{description:this.props.row.Description}}}>
                        {this.props.row.Occupation}
                    </Link>
                </td>
                <td>{this.props.row.Description}</td>
            </tr>
        )
    }
} 

index.js

<Route path="/Topics/:Occupation/:objectId/:id/:userName" component={Main} />

I want to pass it here and access the state given in Link tag. So your help will be great.

4 Answers

After you pass data to the state object in the Link, you can access this data in the routed component(In your case it is the Main component), like this:

props.location.state

You need not pass any extra values to the route. You can achieve what you desire by providing extra objects to the link object.

Something on the lines of -

 <Link to={{pathname:"/Topics/", customObject: customValue}}>

and then you can access it from this.props.location.customObject

According to docs, you can do something like this

<Link to={{ pathname: '/hello', query: { name: 'ryan' } }}> Hello </Link>

And in a new path, you can get that name using props.

I know I am late to provide a solution, you might have got a solution, But my solution can also work for others who are facing the same issue. I have done something like this

public loadPage(data) {
    browserHistory.push({
        pathname: '/am/activate',
        state: data
    });
}

On the other component you can access this value

this.props.location.state
Related