3

I have a react app that acts as a dashboard and displays links for different React applications. Users can select the application by clicking a button.
In short I need to redirect to a different URL based on user selection.

In the sample code below, trying to redirect to a URL using withRouter. However its giving the below error: TypeError: Cannot read property 'push' of undefined

I am using React 15.6.1.

index.js

render(
    <BrowserRouter>
        <Home />
    </BrowserRouter>, document.getElementById('app')
);

home.js

class Home extends React.Component {

    constructor(props) {
        super(props);
        this.loadApp1 = this.loadApp1.bind(this);
    }

    loadApp1() {
        this.props.route.push('/app1');
    }
    render() {
        return (
            <div>
                 <button onClick={this.loadApp1}>App1</button>
            </div>
        );
    }
}

export default withRouter(Home);
Cisco Java
  • 233
  • 3
  • 13

2 Answers2

3

You could use Link to do this:

import { Link } from react-router-dom;

Then,

<button><Link to="/app1">App1</Link></button>

Will route to the App1 route.

For an external site, you could do this:

   loadApp1() {
        window.location = "example.com";
    }
Dream_Cap
  • 2,292
  • 2
  • 18
  • 30
1

Your loadApp1 should be

 loadApp1() {
    this.props.history.push('/app1');
}
palsrealm
  • 5,083
  • 1
  • 20
  • 25