简体   繁体   中英

How to redirect on button click in ReactJS

I want to redirect to './createadd.js' on click (when the function runs). How can I? i have tried using history.push() and react router but none works.

APP.JS:

import { render } from '@testing-library/react';
import React from 'react';

class App extends React.Component {
  render(){

  this.selladd = () => {     //Function to redirect to another page

  }

  return (
  <div style={{position: "absolute", left: 1300, top: 25, overflowX: "hidden"}}>
    <button onClick={this.selladd}>Sell</button>
  </div>);
    }
}

export default App;

You can use both the link and the history.push()

 import { render } from '@testing-library/react';
    import React, { Component } from 'react';
    
    class App extends React.Component {
 constructor(props) {
        super(props);
this.selladd =this.selladd .bind(this);
}
selladd (){
 this.props.history.push({ pathname: ''  })
}
      render(){

      return (
      <div style={{position: "absolute", left: 1300, top: 25, overflowX: "hidden"}}>
        <button onClick={this.selladd}>Sell</button>
      </div>);
        }
    }

or

import { Link } from 'react-router-dom';
     <Link to={{ pathname: '' }}  >
     <button onClick={this.selladd}>Sell</button>
      </Link>

You need to redirect to another component which is in file createadd.js right.

Wrap your component as:

export default withRouter(App)

And add a path to your routes such as:

<Route exact path='/createadd' component={CreateAddComponent} />

Where CreateAddComponent, is you component imported from the createadd.js file.

Then in your function, just do

this.props.history.push('/createadd')

You can redirect to any of the pages using

this.props.history.push("your link here");

Or if you are using react-router-dom, you can also use

<Redirect to="path" />

Or why don't you just wrap your button inside a href tag.

<a href ="link"> 
   <button>Click Here</button>
</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM