I'm trying to change the page in react-router by calling history.push
method. but I need an event to listen to page url changes and update context by getting query parameters. how can I declare that event?
Asked
Active
Viewed 104 times
1

reza
- 1,746
- 6
- 16
- 32
-
2Try `componentDidMount`. – ravibagul91 Dec 10 '19 at 12:24
-
how? would u clearify? I want to use those params in several components and it's changing from one component. – reza Dec 10 '19 at 12:46
-
Possible Duplicate of [Detect Route Change with react-router](https://stackoverflow.com/questions/45373742/detect-route-change-with-react-router/45373907#45373907) – Shubham Khatri Dec 10 '19 at 12:46
-
@ShubhamKhatri i want that listen method outside of
component. but it's not possible. – reza Dec 10 '19 at 13:19 -
You could have wrap your Top level component with Router – Shubham Khatri Dec 11 '19 at 05:20
2 Answers
0
One way to do it is to change the state with the url parameters right after history.push
(which is synchronous) which will update your UI.
Reading url parameters from url should be done only on initial mount.

Emmanuel Meric de Bellefon
- 2,319
- 1
- 11
- 25
-
but I'm using parameters in another component and the only way to share those variables is using context – reza Dec 10 '19 at 12:44
-
ok, one other way is to lift up the props to the closest common ancestor, or to use Redux. – Emmanuel Meric de Bellefon Dec 10 '19 at 12:58
0
You can send the data required on the next page in history.push
.
this.props.history.push("/url", { id: 123 })
then you can access the parsed data in the next component by following code,
const state = this.props.location.state

akhil choudhary
- 913
- 6
- 7
-
I don't want using props to pass data through components. because this data is used in several component and 'll mess in code – reza Dec 10 '19 at 13:21