In react I can use this.props.history in Route components or using withRouter. But I want to access this globally from others components. Is there any way? Thanks in advance.
In react I can use this.props.history in Route components or using withRouter. But I want to access this globally from others components. Is there any way? Thanks in advance.
Assuming you're using at least React 16.8.0 when hooks were introduced, the useHistory hook will give you access to the history instance. This is essentially the modern equivalent of the withRouter HOC you mention in your question. Is there a reason this does not fit your needs?
You mention accessing it "globally", which makes me think you're looking for something like assigning the history instance to window, which you could of course do, but the hook/hoc are the more canonical approaches to getting access to history from a component.
As the comment said, you can use react context, or redux to pass your history to all the child components.
And, here is one solution about how you can catch the history via local HOC.
component={BK} => component={RouteWithHistory(BK)}
ReactDOM.render(
<Provider store={store}>
<ThemeProvider theme={theme}>
<BrowserRouter>
<Switch>
<Route exact path="/books" component={BK} /> // Before
<Route exact path="/books" component={RouteWithHistory(BK)} /> // After
<Route path="/details/" component={DT} />
<Redirect to="/" />
</Switch>
</BrowserRouter>
</ThemeProvider>
</Provider>
,document.getElementById('root')
);
And the main function
interface Props {
history: {location: {pathname: string}};
}
const RouteWithHistory = (Component: React.FC) => (props: Props) => {
const pathname = props.history.location.pathname;
console.log(pathname);
// You can use redux here.
// Or use the react context as below.
const ThemeContext = React.createContext('');
return (
<ThemeContext.Provider value={pathname}>
<Component />
</ThemeContext.Provider>
)
}