0

Background I'm migrating from v4 to v6. Many of my pages are class components, not functional components, and I relied heavily on RouteComponentProps (written with Typescript):

export class UserDashboard extends React.Component<RouteComponentProps> {
  constructor(props){
    super(props);
    this.updateURL = buildURLUpdater(props.history, props.location, ...);
    console.log(props.user);
  }

  onChooseUser = (newUser) => {
    this.setState({
      user: newUser
    }, this.updateURL);
  }

  ...
}

<Switch>
  <Route path="/users">
    <Users focusUser={user} />
  </Route>
</Switch>

Question I know that React Router V6 relies heavily on hooks, but I'm not sure how to get location or history in a class component. Is this still possible?

Why I wrote a handy function that I can run after every setState command that would automatically update the URL and insert a history item without having to navigate. This would be for when I want the current search text to show up in the URL bar as the user types. I used props.location and props.history to do that. So if I can't get route component props anymore, I need a way to grab the history and location object, or whatever its V6 equivalents are, in the constructor of a class.

whiterook6
  • 3,270
  • 3
  • 34
  • 77
  • 1
    Does this help answer your question? https://stackoverflow.com/a/64566486/8690857 To update the queryString params you'd use the `useSearchParams` hook. – Drew Reese May 24 '22 at 21:07
  • @DrewReese Maybe. I have to use a wrapper to grab the values from hooks and pass them on? – whiterook6 May 24 '22 at 21:10
  • 1
    Yes, you have to user either a wrapper component and pass them along, or create a `withRouter` HOC replacement to do the same. – Drew Reese May 24 '22 at 21:12

0 Answers0