6

Can anyone help me regarding how to use meta tags with dynamic value in react js?

Please see the image for my requirement,

code screenshot

I am using the extra metatag html tag here(because react require wrap complete html inside the single tag else it raise error). I can also use div/p any html tag, but is this right way to render the react component? having extra html tag than inside that meta tags. Will this work for SEO?

Please suggested me any other good way to use meta tags manually.

5 Answers 5

8

I can see few issues regarding the code which you shared.

  1. Meta tags come under head, but your react components would be rendered in your body tag.
  2. Considering SEO part, google can parse JS now so your tags would be read but bing and if you consider yahoo still cannot still do that( Google also is really not that efficient still, faced too many issues regarding while handling SEO's with single page app)
  3. If your reacts components uses Link to navigate to other components which I am assuming it would it case of SPA it would not work, because crawlers try to reach you page directly.

Now,if you have a single page app with a single component you can try react-helmet , but if it involves multiple components and navigations I would suggest you to go for pre-rendering,maybe using phatom-js or pre-render.io(which indirectly uses phantomjs).

If your only concern is meta tags, then you can embed you meta tags directly into your html code and not in the components. This would really help the crawlers to see the meta tags.

But,if you also want crawlers to see your content, pre-rendering is best solution which I can think of now.

Sign up to request clarification or add additional context in comments.

Comments

5

If you are serving your React bundle from a server, you can dynamically generate meta tags on the server.

Essentially, in your public/index.html file you want to replace the metadata with an identifiable string:

<!-- in public/index.html -->
<title>$OG_TITLE</title>
<meta name="description"        content="$OG_DESCRIPTION" />
<meta property="og:title"       content="$OG_TITLE" />
<meta property="og:description" content="$OG_DESCRIPTION" />
<meta property="og:image"       content="$OG_IMAGE" />

And then on the server, you want to replace these strings with the dynamically generated information. Here is an example route with Node and Express:

app.get('/about', function(request, response) {
  console.log('About page visited!');
  const filePath = path.resolve(__dirname, './build', 'index.html')
  fs.readFile(filePath, 'utf8', function (err,data) {
    if (err) {
      return console.log(err);
    }
    data = data.replace(/\$OG_TITLE/g, 'About Page');
    data = data.replace(/\$OG_DESCRIPTION/g, "About page description");
    result = data.replace(/\$OG_IMAGE/g, 'https://i.imgur.com/V7irMl8.png');
    response.send(result);
  });
});

Taken from this tutorial here: https://www.kapwing.com/blog/how-to-add-dynamic-meta-tags-server-side-with-create-react-app/

Comments

5

** no need to install express node and all..
** just add react-helmat & must add Helmat-meta tag all routing container. (otherwise its still show home page meta tag) ** react return single element, so you must add into parent element like (div, form)

import { Helmet } from "react-helmet";
import MetaDataJSON from "./MetaDataJSON_File"; 

constructor(){
    this.metaDetails = {}; 
}

UNSAFE_componentWillMount(){
    let curPath = window.location.pathname
    this.metaDetails =  getMetaData(curPath);   
}

export const getMetaData = (pathname) =>{
  const metaObj = MetaDataJSON;      // import meta json and check the route path is in equal to your meta json file        
  let metaPath = Object.keys(metaObj);
  if (metaPath.indexOf(pathname) >= 0) {
    return metaObj[pathname]; 
  }else{
    return metaObj["/"]; 
  }
} 

// you must add in all component (where routing container)
render(){ 
    return(
        <div>
            <Helmet>
                <title>{this.metaDetails.title}</title>
                <meta name="description" content= {this.metaDetails.description}/>
                <meta name="keywords" content= {this.metaDetails.keywords} />
            </Helmet>
        <div>
    )
}

5 Comments

This works really nice thank you! IMHO You could improve your answer by linking the package npmjs.com/package/react-helmet and simply referencing/copying their code example. Their code example helped me to understand how easy this package is even better :)
no that is not working. seo does not recognize new meta tags.
Are meta tags showing in page view source?
what about sharing it to Facebook and other social networks? will the new meta data show >
this is not working, helmet is not able to show the meta data on sharing on social networks
4

Create React App produces a static bundle with HTML, JS, and CSS. It can’t possibly give you a dynamic <meta> tag because the result HTML is created ahead of time.

While changing document.title with something like React Helmet makes sense, changing <meta> tags doesn’t make sense unless your app is server rendered. Server rendering is not a supported feature of Create React App so if you want to use it, you might want to check out some alternatives such as Next.js.

That said, if you don’t want full server rendering and only need to change <meta> tags, you could do this by hand as described here.

I hope this helps!

Comments

3

There Is a Package Named React-Helmet available it helps to take control over Your Head tags on each route. Helmet takes plain HTML tags and outputs plain HTML tags. It’s dead simple, and React beginner friendly.

<Helmet>
     <title>{context.StoreName}</title>
     <meta name="theme-color" content={`${context.ThemeColor}`}/>
</Helmet>

reference - https://codeburst.io/how-to-control-head-tags-in-react-seo-friendly-8264e1194880

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.