skip to Main Content

this is Alex, i am new to react, while i was learning from the video, he was not using react v6, so i type this.props.history.push(‘/add-employee’); it won’t work. Can somebody help me with the navigation in react v6code. Thanks!

2

Answers


  1. If you still want to use react-router-dom v6 (see advice at the end of the answer), you can use useNavigate hook to achieve this

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

    then in your functional component instead of this.props.history.push('/add-employee');

    //inside the function at the top
    const navigate = useNavigate();
    
    // use this in replace of 'this.props.history.push('/add-employee');'
    navigate('/add-employee');
    

    Some advice related to the tutorial that you are following

    • Install same dependencies that are used in the tutorial
    • OR follow another tutorial that is more up to date
    Login or Signup to reply.
  2. It is easier to use a function component instead, where the useNavigate hook can be called.

    Then, navigating to a new route can be done like so:

    import { useNavigate } from 'react-router-dom';
    function MyComponent() {
        const navigate = useNavigate();
        function addEmployee() {
            navigate('/add-employee');
        }
        // return some JSX...
    }
    

    For this to work with class components, you would need to create a function component wrapper.

    const withNavigate = Comp => props => <Comp {...props} navigate={useNavigate()} />;
    class MyClassComponent extends React.Component {
        addEmployee = () => this.props.navigate('/add-employee');
        // ...
    }
    const MyComponent = withNavigate(MyClassComponent);
    // now only use MyComponent instead of the class component
    export default MyComponent; 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search