TyForHelpDude
TyForHelpDude

Reputation: 5002

passing props within react router with history object

import createBrowserHistory from 'history/
import appState from './AppState'

const customHistory = createBrowserHistory()
ReactDOM.render(
  <Router>
    <div>
      <Route path="/submit" component={Submit} history={history}/>
    </div>
  </Router>,
  document.getElementById('root')
);

Notice: if I add appState like other properties; there is not property such as appState in Submit component,

if I use this;

<Route path="/submit" render={routeProps=> <Submit appState={appState}/> history={history}/>

appState pass fine but this time history object is missing, what is proper way of doing this? appState is just mobx class instance.

EDITED: I found a "weird" solution. i changed route element to this;

 <Route path="/submit" render={routeProps=> <Submit appState={appState}/> history={history}/>

then I am able to access same history object via this._reactInternalInstance._context.router.history.push('/home') before I made this change i was able to use it as this.props.history.push('/home')

if I leave this as it works fine but its annoying getting this history object with this way

Upvotes: 0

Views: 1076

Answers (2)

degr
degr

Reputation: 1565

You are doing wrong, I'm sure in it. Browser history is a singleton object, so you can export it from module. Look here:

//history.js:
import createBrowserHistory from 'history/
export default createBrowserHistory();

//Submit.js
import history from "myapp/history"
export default class Submit extends React.Component {
   ...
}

//MyRouter.js
import Submit from './myapp/Submit'
import appState from './AppState'
ReactDOM.render(
  <Router>
    <div>
      <Route path="/submit" component={Submit}/>
    </div>
  </Router>,
  document.getElementById('root')
);

Upvotes: 1

Hana Alaydrus
Hana Alaydrus

Reputation: 2220

I think it's right, better for you to put the history in Router not Route.

See below answer, this one work well on me. You still can use history.push in this answer. Sometimes history.push didn't redirect the page. if this happen to you, you can put location.href = location.href to refresh the page.

https://stackoverflow.com/a/42679052/7765396

Upvotes: 2

Related Questions