Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router v4.0 - Redirect to a page outside of Router scope

I'd like to be able to navigate to a home page outside of "subpage" defined in a < Router >. Here's my component.

import * as React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

import { Search } from './page/Search';
import { Quote } from './page/Quote';

export class MainContent extends React.Component<{}, {}> {    
    redirectToHomepage(){
        // something.push('/')
    }

    render() {
        return (
            <div id="main">
                <button onClick={this.redirectToHomepage}>
                    Back Home
                </button>
                <Router>
                    <div>
                        <Route exact path="/" component={Search} />
                        <Route path="/quote" component={Quote} />
                    </div>
                </Router>
            </div>
        );
    }
}

export default MainContent; 

By clicking on a button, I'd like to return to a homepage. Inside the { Search } component, I'm able to go to a page using this.props.history.push('/quote');

But how can I do it from the MainConent Component?

Thank you

like image 521
Marián Zeke Šedaj Avatar asked Nov 09 '22 00:11

Marián Zeke Šedaj


1 Answers

You can import the browserHistory and use the 'push' method i think:

import { browserHistory }  from 'react-router;

redirectToHomepage(){
    browserHistory.push('/home');
}

Update react-router 4: Now you need to use Redirect component from 'react-router-dom', some like:

render() {
  render (
    { this.props.authenticated ? 
      (<Redirect to={{ pathname: '/', state: { from: this.props.location }}} />) :
      (<div> Content</div>)}
  )
}
like image 70
Giancarlos Avatar answered Nov 14 '22 22:11

Giancarlos