-1

I am trying to pass the selected Id of an account when a user clicks the click zone.

<Link to="/account" id={1234}>

However, on my Account component, which this 'to' takes us to:

<Route path="/account" component={Account}/>

I am getting Undefined.

export default class Account extends Component {
    constructor(props) {
        super(props);

        alert(props.id);

Is there a way to pass the prop to my component using the Link?

Craig
  • 18,074
  • 38
  • 147
  • 248

3 Answers3

1

I think the best way would be define your account id as parameter in the route e.g.

<Route path="/account/:id" component={Account}/>
<Link to='/accounts/123'> Go to Accounts</Link>

and access it with props.match.params.id, but if you want to send through props you do this:

<Link to={{ pathname: '/account', state: { id: '123'} }}>Go to Accounts</Link>

and in Account:

const { id } = props.location.state
erich
  • 261
  • 5
  • 12
0

To pass props down to children you can do this

<Route
 path="/new/path"
 render={(routeProps) => (
   <MyComponent {...routeProps} {...props} />
 )}
/>

and don't skip the spread operators.

illiteratewriter
  • 4,155
  • 1
  • 23
  • 44
0

A clean way for a link to pass information to a route is to use a parameter in the URL:

// 1. Link to what would be the URL for a specific account.
// would probably replace `1234` for a variable here
<Link to={`/account/${1234}`>View Account 1234</Link>

// 2. "capture" the ID in the url using a param matcher
// We'll receive this param as "props.match.params.id" in the render function
// using component={} also works here, and the props will be injected directly into the component instead,
// but render={} here looks cleaner to me, and is more flexible if you wanna pass more props
<Route path="/account/:id" render={props => <Account id={props.match.params.id} />} />

See the docs for more information on how the render prop works.

kingdaro
  • 11,528
  • 3
  • 34
  • 38