Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
How to do routing in react by clicking a button in class component?

I was having a button in a react class component as following

 <Link to="display">
    <button onClick={this.nextBtn} className="nextBtn">
        Submit
    </button>
 </Link>

By clicking the button, I need to route it to another component called <Display /> using the function nextBtn = () => {}.

I saw that in the function component it can be by useHistory but in the class component, I don't know how to do it.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can also use withRouter from import { withRouter } from "react-router"; and inject your component. You can get history as a props and use history.push() for navigate route.

Example:

import React from "react";
import { withRouter } from "react-router";

class ShowTheLocation extends React.Component {
  nextBtn = () => {
    const { history } = this.props;

    history.push("/display");
  };

  render() {
    return (
      <Link to="display">
        <button onClick={this.nextBtn} className="nextBtn">
          Submit
        </button>
      </Link>
    );
  }
}

export default withRouter(ShowTheLocation);
about 4 years ago · Juan Pablo Isaza Report

0

You can also try this. It's works for me

import { browserHistory } from 'react-router';
    class MyClass extends Component {
        nextBtn = () => {
           browserHistory.push('/display');
        }
    }
about 4 years ago · Juan Pablo Isaza Report

0

You can route to another page using several methods. First, in your case, you are using a Link. But your route name passing is wrong. You have to pass the route name in front like this:

        <Link to={'/display'}> 
        // display should be a routes name
         <button className="nextBtn">
         Submit
         </button>
         </Link>

https://reactrouter.com/web/api/Link.

You can read more about it here:

Secocnd method:
Use react-router-dom package to define the routing and then use one of below mentioned ways on onClick event of button.

  1. this.props.history.push("componentpath").
  2. browserHistory object (in react-router package).

Also check this question solutions... how to navigate from one page to another in react js?

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!