Navigation in React-Router v6

Hey Mosh,

in your course I’ve learned to Redirect after submitting a form with this.props.history.push("/movies");

It appears not to work in router v6, where it’s recommended to use the UseNavigation Hook. But in the course we are building a movieForm as a class component in which Hooks do not work like in functional components.

Do you have any suggestions how to use hooks in classes, or how to refactor classes to functional components which should be used in v6 over class components?

Thanks for your help

Hi.
I did stop coding in React for a few months so I’m very new to these new versions. So your question is interesting.
I did use React Dev Tools to see how it looks like and all the information that used to be provided via props is now located at different levels of the routing tree.

Now the official documentation says you either use the <Link /> component which fits for navigation bars or useNavigate hook when you need to navigate programmatically.

Tested them (<Link /> and useNavigate) and it works fine.

Best regards.

P.S. : I realise I did not really answer your question.
I will look into it and try to come back with my results.

OK I did it.
So I applied what is explained in this article. Just I code in JS instead of TS but that’s very close and easy to switch from one to the other.

So here is my code:

I create an HOC (Higher-Order Component) that wraps our target component

import React from 'react';
import { useNavigate } from 'react-router-dom';

const withNavigateHook = (Component) => {
    return (props) => {
        const navigation = useNavigate();

        return <Component navigation={navigation} {...props} />
    }
}

export default withNavigateHook;

Then I apply the HOC to the target component

import React, { Component } from 'react';
import withNavigateHook from '../withNavigateHook';

export class ClassPage extends Component {
    constructor(props) {
        super(props);
        this.handleToContact = this.handleToContact.bind(this);
    }

    handleToProduct = () => {
        console.log("To product");
        this.props.navigation('/product');
    }

    handleToContact() {
        console.log("To contact");
        this.props.navigation('/contact');
    }

    render() {
        return (
            <div>
                <button onClick={this.handleToProduct}>To Product</button>
                <button onClick={this.handleToContact}>To Contact</button>
            </div>
        )
    }
}

export default withNavigateHook(ClassPage);

Just as before I tried and it works.

Best regards.

1 Like

thank you so much.my error was solved.

1 Like