Como redirecionar ao clicar no botão do ReactJS

Sep 29 2020

Quero redirecionar para './createadd.js' no clique (quando a função for executada). Como posso? Eu tentei usar o history.push () e o roteador react, mas nenhum funciona.

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;

Respostas

1 HimanshuTariyal Sep 29 2020 at 18:28

Você pode redirecionar para qualquer uma das páginas usando

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

Ou se você estiver usando o react-router-dom, você também pode usar

<Redirect to="path" />

Ou por que você simplesmente não envolve o botão dentro de uma tag href.

<a href ="link"> 
   <button>Click Here</button>
</a>
1 MubashirEbad Sep 29 2020 at 18:13

Você precisa redirecionar para outro componente que está no arquivo createadd.js correto.

Envolva seu componente como:

export default withRouter(App)

E adicione um caminho às suas rotas, como:

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

Onde CreateAddComponent, é seu componente importado do arquivo createadd.js.

Então, em sua função, basta fazer

this.props.history.push('/createadd')
1 zahrazamani Sep 29 2020 at 18:09

Você pode usar o link e o 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>);
        }
    }

ou

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