pbuzz007
pbuzz007

Reputation: 947

React triggering navigation from nested components

I am new to React/RN and understand how navigation works, but don't really see a best practices for how to trigger navigation from a trivial component, like a random button somewhere, that should trigger a route change.

Let's say this button is nested under a set of elements who are under a <Tab.Navigator> who are under a set of <Stack.Navigator>, etc. A couple screen layouts deep. This element cannot access this.props.navigation. So my idea is to send upwards. But this could mean passing an onPress handler like, 5 or 6 layers down. Is this the correct way? Should I only pass it from the parent closest to a navigator, or all the way to App.tsx?

Upvotes: 0

Views: 162

Answers (1)

user9760669
user9760669

Reputation:

If you can not use the <Link> component, then you should use the history object.
For example, the useHistory hook will return it ( whenever you will import ),
so your component can be nested as hell.

import { useHistory } from 'react-router-dom'

function HomeButton() {
  const history = useHistory()

  function handleClick() {
    history.push('/home')
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  )
}

Upvotes: 1

Related Questions