skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. You can listen window.location changes using popstate event

    In React component you can use the useEffect hook along with the window.addEventListener method

     useEffect(() => {
        const locationChange = () => {
          console.log(window.location.href);
        };    
        window.addEventListener('popstate', locationChange);
    
        // Cleanup function
        return () => {
          window.removeEventListener('popstate', locationChange);
        };
      }, []); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search