0

How to navigate by using withRouter in reactJS while clicking on button react-router 6.2.1.

I am using react "react-router": "^6.2.1","react-router-dom": "^6.2.1",

I am getting error by

export 'withRouter' (imported as 'withRouter') was not found in 'react-router-dom'

Here is my code.

import React, { Component } from "react";
import { withRouter } from 'react-router-dom'; 

class myTab extends Component {
constructor(props) {
    super(props);
        this.state = {};
}

createNew = () =>{
    this.props.history.push(`/new/`);
}

render() {
    return (
      <div>
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <div class="container-fluid">
                <button type="create" class="btn btn-primary" width="300"  onClick={this.createNew}> New </button>
               
            </div>
          
        </nav>
      </div>
    );
  }
}

export default withRouter(myTab);

Even though I am downgrading react router to 5.2 I am getting the same errror.

What options i have to fix this.

David
  • 4,266
  • 8
  • 34
  • 69
  • I'm quite certain `withRouter` was removed since v5, so if you want to fix this downgrade to v4 or use another implementation. – code Feb 26 '22 at 05:24
  • I checked it with react-router-dom 5.3.0 and it's working fine. Maybe you need to restart your development server after downgrading to the version 5.2 – Shivam Mishra Feb 26 '22 at 05:31
  • 1
    Reverting back to `react-router-dom@5` will work for you if you want to keep using the older code and exported `withRouter`, otherwise you'll need to create a custom `withRouter` to inject the `navigate` function as a prop to work with the class component, or convert the class components to function components and use the hooks directly. – Drew Reese Feb 26 '22 at 05:32
  • @code whatis the alternate option we have in v6. – David Feb 28 '22 at 03:38
  • https://stackoverflow.com/a/69934614/15359157 – code Feb 28 '22 at 03:43

0 Answers0