0

I'm trying to pass props from one component into a Class component via a <Link> using React-Router.... But I'm having trouble...

I have this code in one component wrapping text/image:

<Link to={{ pathname: "/newPage", state: {userName: uName, userGender: uGen}}}>
   <img src={newIcon}> Link text goes here</img>
</Link>

(uName & uGen are consts which are generated in code above)

and in my Class page I have:

class NewPage extends React.Component<Props, State> {

constructor(props: any) {
  this.state = {
    userName: '',
    userGender: '',
  }
}

render() {
  return (
   ...Content goes here...
   {userName} & {userGender}
  )
 }

}
export default NewPage 

This renders the new page, but for the life of me I can't access the props I'm trying to pass into it. Can anyone point me in the right direction as to what I'm doing wrong? I'm very new to this...

Thanks in advance for any pointers :)

Rob BB
  • 1
  • 1

1 Answers1

0

I think you've misunderstood react-router and react a little.

Using the Link props, you are actually pushing into the history location's state, and you need to pick these up in the component.

Assuming the component must be a class, you can wrap it with withRouter provided by react router. Alternatively you can use hooks provided by react-router (I won't write examples as it depends on your version but check the docs).

If your component lives directly inside a Route component and already has access to this.props.history you can skip this step.

class NewPage extends React.Component<Props, State> {

constructor(props: any) {
  this.state = {
    userName: '',
    userGender: '',
  }
}

render() {
  return (
   ...Content goes here...
   {userName} & {userGender}
  )
 }

}

export default withRouter(NewPage) 

then you need to fetch from the location state in the constructor:

constructor(props: any) {
  this.state = {
    userName: props.history.location.state.userName || '',
    userGender: props.history.location.state.userGender || '',
  }
}
pacifica94
  • 725
  • 2
  • 6
  • 13
  • Thanks pacifica94. I think I'm gonna have to go back to the drawing board and dump the class component. If 'class' isn't the way to go, what would be the best method to render this page? – Rob BB Jan 26 '23 at 16:29
  • There's nothing wrong with class components and they still have their uses so I wouldn't jump straight into refactoring, but the modern approach is to use functional components with hooks. The main benefit in my work is that you can encapsulate and reuse lifecycle/event or other logic in hooks across different components – pacifica94 Jan 27 '23 at 09:07