Home > Back-end >  How to navigate through routing on button click in react. react-router": "^6.2.1
How to navigate through routing on button click in react. react-router": "^6.2.1

Time:03-20

How to navigate through routing on button click in react.

I am trying to acess some other class using routing ( "react-router": "^6.2.1",) in reactJS. When I am clicking I am getting this error.

Cannot read properties of undefined (reading 'push')

Here is my class

import React, { Component } from "react";
import { withRouter } from 'react-router-dom';  
import { useHistory } from "react-router-dom"; 
import Button from "@mui/material/Button";

class MyBar extends Component {
constructor(props) {
    super(props);

        this.state = {};
        this.createNew = this.createNew.bind(this);
}

createNew () {
   this.props.history.push('/new');
}

render() {
    return (
      <div>
        <nav >
            <div >
                 <div >
                    <button type="create"   onClick={this.createNew}> Create Post </button>
                  </div>
            </div>
        </nav>
      </div>
    );
  }
}
export default MyBar;

Here is my dependency

"dependencies": {
    "@emotion/react": "^11.8.1",
    "@emotion/styled": "^11.8.1",
    "@mui/material": "^5.4.3",
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.3",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.26.0",
    "bootstrap": "^5.1.3",
    "draft-js": "^0.11.7",
    "font-awesome": "^4.7.0",
    "react": "^17.0.2",
    "react-bootstrap": "^2.1.2",
    "react-dom": "^17.0.2",
    "react-draft-wysiwyg": "^1.14.7",
    "react-icons": "^4.3.1",
    "react-pro-sidebar": "^0.7.1",
    "react-router": "^6.2.1",
    "react-router-dom": "^6.2.1",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.4"
  },

But in other version( "react-router-dom": "^5.2.0",) of app by using this in the export

export default withRouter(ListOfEmployee);

I was easily able to navigate.

Can anybody help me here.

PS: I know there are multiple answer but none of them are its working and not getting much from the git and offcial docs.

CodePudding user response:

In v6 you can use useNavigate:

const navigate = useNavigate()
navigate('/new')

CodePudding user response:

It should work

class Login extends Component {
    nextPath(path) {
    this.props.history.push(path);
  }
    render() {
        return (
        <div>
        <button type='button' onClick={() => this.nextPath('/yourpath') } >Button</button>
        </div>
        );
}
        
  • Related