How to redirect to another page on button click in Reactjs

jung lee picture jung lee · Sep 26, 2019 · Viewed 22.8k times · Source

I want to create a basic web application using react. I have implemented creating buttons. I want to redirect to another page on button click. Below is my App.js code

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
        <p>
          <buttontoolbar>
            <button const path = '/Components'> Click Me </button>
          </buttontoolbar>
        </p>
     </header>
    </div>

  );
}

export default App;

When i click on 'click me' button it should redirect to Components.js. Below is the code for Components.js

import React from "react"

function app(){
 return(
  <p>
  Welcome to the world. 
  </p>
 )
}

export default app

Long back i have done these king of things in ASP.NET. there i have used Response.redirect to redirect pages which is so simple. As I am new to React, i know nothing about this. Is there anything like that in React?

Answer

Sandeep Rasgotra picture Sandeep Rasgotra · Sep 26, 2019

Use react-router-dom package to define 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).

Please refer this Link