0

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

Edit:
I use i18next and if I use window.addEventListener('popstate', I got the error message Invalid hook call. Hooks can only be called inside of the body of a function component.

chraebsli
  • 184
  • 12

2 Answers2

0

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.

Muhammad Kamal
  • 1,169
  • 1
  • 8
  • 11
-1

To trigger a re-render of your React component when window.location.href changes, you can make use of the useEffect hook and the window.onpopstate event listener.

Here's an example of how you can achieve this:

    import React, { useEffect } from 'react';
import { Helmet } from 'react-helmet';

const MyComponent = () => {
  useEffect(() => {
    const handleLocationChange = () => {
      // Perform any logic you need when the location changes
      // For example, update the title with react-helmet
      Helmet.setTitle('New Page Title');
    };

    // Attach the event listener when the component mounts
    window.addEventListener('popstate', handleLocationChange);

    // Clean up the event listener when the component unmounts
    return () => {
      window.removeEventListener('popstate', handleLocationChange);
    };
  }, []);

  return (
    <div>
      {/* Component content */}
    </div>
  );
};

export default MyComponent;

In this example, the useEffect hook is used to set up the event listener for the popstate event, which is triggered when the URL changes. The event listener calls the handleLocationChange function, where you can perform any necessary logic, such as updating the title using react-helmet.

Make sure you have the latest versions of React and react-helmet installed to ensure compatibility.

  • Thanks, but I got the error `Invalid hook call. Hooks can only be called inside of the body of a function component.`. I think that's because I'm using `react-i18n`. Is there another possibility? – chraebsli Jun 07 '23 at 13:43