RomaValcer
RomaValcer

Reputation: 2956

Implicitly passing router history

I am making a web app with react-router that has navigation similar to mobile stack navigation. The content of a page is supposed to be wrapped in NavigationScreen object (that controls the sidebar, navbar and the works):

class HomeScreen extends React.Component {
  render() {
    return (
       <NavigationScreen>
         <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
           <Text>Home Screen</Text>
           <Link to='/details'>details</Link>
        </View>
       </NavigationScreen>
    );
  }
}

And the routes are made like this:

export default class App extends React.Component {
  render() {
    return (
      <BrowserRouter>
        <View style={{ position: 'absolute', top: 0, bottom: 0, left: 0, right: 0 }}>
          <Route exact path='/' component={HomeScreen} />
          <Route path='/details' component={DetailsScreen} />
        </View>
      </BrowserRouter>
    );
  }
}

But I think I made an error in the planning. I want the navigation bar to have a "back button", which should work by invoking this.props.history.goBack. The thing is that the HomeScreen class receives this prop, and not the NavigationScreen. The only solution I can see is making a rather awkward prop passing:

class HomeScreen extends React.Component {
  render() {
    return (
       <NavigationScreen history=this.props.history>
         <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
           <Text>Home Screen</Text>
           <Link to='/details'>details</Link>
        </View>
       </NavigationScreen>
    );
  }
}

Looks pretty bad IMO, is there a better way?

Upvotes: 0

Views: 72

Answers (1)

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36179

You may want to use withRouter HOC on NavigationScreen if you don't want to pass history as a prop.

Upvotes: 3

Related Questions