1

I am trying to navigate to another component whenever the "Send Questions" button is clicked.

This was my attempt:

<p>
  {(this.state.hide) && (
    <button 
      style={{ background: "green", color: "white" }}
      onClick={()=> {this.props.history.replace('/questions')}}
    >
      Send Question
    </button>
  )}
</p>

However I get the following error

Search.js:115 Uncaught TypeError: Cannot read property 'replace' of undefined

Following are my imports related to routing

import { Route } from 'react-router';
import { withRouter } from 'react-router-dom';
import { BrowserRouter as Router } from 'react-router-dom'
2
  • Maybe just use the <Link/> from react-router-dom like this <Link to="/questions">About</Link> and declare the route in your router? Commented Apr 15, 2018 at 11:07
  • @davidbucka I want to use buttons instead of links Commented Apr 15, 2018 at 11:11

1 Answer 1

1

Most likely you didn't wrap your component withRouter

class YourComponent extends React.Component {
  render() {
    return (
       ... 
       <button onClick={() => this.props.history.replace('/questions')}>
       ...
    );
  }
}

export default withRouter(YourComponent);

Another simple solution where you don't need to use withRouter

import * as React from 'react';
import { Link } from 'react-router-dom';

export default YourComponent extends React.Component {

  render() {
    return (
      ...
      <p>
        { this.state.hide && (
          <Link to="/questions">
            <button 
              style={{ background: "green", color: "white" }} 
            >
              Send Question
            </button>
          </Link>
        )}
      </p>
      ...
    );
  }
}

Also note: if you want to replace the current URL you should use this.props.history.replace but if you want to navigate the User to a new page (which is what you most likely you want to do. You should use this.props.history.push instead)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.