1

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;

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

It's giving error saying: Cannot read property 'push' of undefined. Do i have to define history as " const history = useHistory(); " ?
No you don't have to. History is passed down to the child components automatically. You don't have to define it. There can be many reasons for why it is throwing error. Refer to this link stackoverflow.com/questions/53712860/…
1

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')

1 Comment

Its giving: Expected an assignment or function call and instead saw an expression.How to fix it? I have put the <Route /> right before the " export default withRouter(App) " ?
1

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.