Reputation: 274
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.
Upvotes: 6
Views: 14453
Reputation: 11
1.Use this sample code
2.Passing Data(object):
import { Link } from 'react-router-dom';
/* ... */
const myData = {
name: 'Some thing',
price: 123
}
/* ... */
<Link to="/some-where" state={myData}>Link Text</Link>
3.Retrieving Data(object):
import { useLocation } from 'react-router-dom';
/*...*/
const location = useLocation();
const data = location.state;
console.log(data);
For more: https://www.kindacode.com/article/react-router-passing-data-states-through-links/
Upvotes: 0
Reputation: 864
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
Upvotes: 3
Reputation: 4537
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
Upvotes: 5
Reputation: 2457
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.
Upvotes: 3
Reputation: 390
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
Upvotes: 5