Skip to content
Advertisement

Rewriting React router v4 class based code to v6 functional based

I’m trying to implement oauh login with react and spring boot and I’ve found a tutorial I can follow.

The issue I have is that it is using React Router v4, I would like to update it to use React Router v6 and using Functional components instead.

Login.js

JavaScript

App.js

  • This is the App.js with the routes, I have updated it to use Functional components and React Router v6.
JavaScript

What I would like clarity on

  1. I’m struggling to understand the equivalent of the react router functionalities with v6 (location.state.error, history.replace, location.pathname etc) and functional components instead of class based.

  2. Also, If someone can explain this line please <LoginForm {...this.props} />

Advertisement

Answer

Q1

I’m struggling to understand the equivalent of the react router functionalities with v6 (location.state.error, history.replace, location.pathname etc) and functional components instead of class based.

In react-router-dom v6 there are no longer route props, i.e. no history, location, and no match. The Route components also no longer have component or render props that take a reference to a React component or a function that returns JSX, instead they were replaced by the element prop that takes a JSX literal, i.e. ReactElement.

If I’m understanding your question(s) correctly you are asking how to use RRDv6 with the class components Login and Signup.

You’ve a couple options:

  1. Convert Login and Signup into React function components as well and use the new React hooks.

    I won’t cover the conversion, but the hooks to use are:

    • useNavigatehistory object was replaced by a navigate function.

      JavaScript
    • useLocation

      JavaScript
  2. Create a custom withRouter component that can use the hooks and pass them down as props.

    JavaScript

    Decorate the Login and Signup exports:

    JavaScript

    Swap from this.props.history.push to this.props.navigate:

    JavaScript

What remains is to fix the routes in App so they are correctly rendering JSX.

JavaScript

Q2

Also, If someone can explain this line please <LoginForm {...this.props} />

This is simply taking all the props that were passed to the parent component and copying/passing along to the LoginForm component.

JavaScript

Login is passed an authenticated prop as well as whatever new “route props” were injected, and any other props injected by any other HOCs you may be using, and the above passes them all along to LoginForm.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement