Skip to content

Export context to allow history access #6365

@TrySound

Description

@TrySound

Ref #6362 (comment)

Since "always render" behaviour will be removed from <Route children /> it would be good to provide a way to access context values from any part of app.

Here's a few ways and all requires to provide RouterContext.

RouterContext.Consumer

const Component = () => (
  <RouterContext.Consumer>
    {context => (
      <button onClick={() => {
        if (context) {
          context.history.push('/users')
        }
      }}>Open users</button>
    )}
  </RouterContext.Consumer>
)

Class component contextType

const Component = class extends React.Component {
  contextType = RouterContext;
  handler = () => {
    this.context.history.push('/users')
  }
}

context.unstable_read api

const Component = () => {
  const context = RouterContext.unstable_read();
  return (
    <button onClick={() => {
      if (context) {
        context.history.push('/users')
      }
    }}>Open users</button>
  )
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions