I have a React component, that should re-render, when window.location.href
changes. This component uses react-helmet and I use it to update the title of the application.
I know I could do it with a page refresh but since only the anchor changes, I don’t want the entire page to reloads but just the component that changes the title with react-helment
.
Versions:
- react: 18.2.0
- react-helmet: 6.1.0
2
Answers
React components rerender when state changes. You can store the title in the component state using the useState hook and update the state when window.location.href changes. In this way the component will rerender.
You can listen window.location changes using popstate event
In React component you can use the useEffect hook along with the window.addEventListener method