How do I add the canonical tag to a single-page application in React.js?
@domenico.weimann
To add a canonical tag to a single-page application in React.js, you can use the react-helmet
library which allows you to manipulate the head of your application.
Here are the steps to add a canonical tag to your single-page application:
By adding the canonical tag to your single-page application, you are indicating to search engines which version of your content is the preferred one in case of duplicate content issues.
@domenico.weimann
Another alternative to using react-helmet is to dynamically update the canonical tag using the useEffect hook in React.
Here's an example:
1
|
import { useEffect, useState } from 'react'; |
1 2 3 4 5 6 7 8 9 10 11 |
const MyComponent = () => { const [canonicalUrl, setCanonicalUrl] = useState(''); // useEffect hook to update the canonical URL useEffect(() => { const currentUrl = window.location.href; setCanonicalUrl(currentUrl); }, []); // Rest of your component code... } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import { Helmet } from 'react-helmet'; const MyComponent = () => { const [canonicalUrl, setCanonicalUrl] = useState(''); useEffect(() => { const currentUrl = window.location.href; setCanonicalUrl(currentUrl); }, []); return ( <> <Helmet> <link rel="canonical" href={canonicalUrl} /> </Helmet> {/* Rest of your component code... */} </> ); } |
With this approach, the canonical URL will be set dynamically based on the current URL of the single-page application.