Skip to content Skip to sidebar Skip to footer

How Can I Add Meta Tags For Sharing A Particular Link In React.js?

Say, I have an online shop application built with React.js and I want to customize the look of the URL that is shared on social media (e.g. add a description and an image) using HT

Solution 1:

Follow the below example step by step to do the same

Step 1 – Install below command Using NPM

npm install react-meta-tags --save

Note: You can also achieve this using React Helmet (a third party library)

Step 2 – Use MetaTag Component in your class Component

importReactfrom'react';
importMetaTagsfrom'react-meta-tags';

classComponent1extendsReact.Component {
  render() {
    return (
        <divclassName="wrapper"><MetaTags><title>Your Page 1</title><metaname="description"content="Your description here.." /><metaproperty="og:title"content="Your App" /><metaproperty="og:image"content="Your path/to/image.jpg" /></MetaTags><divclassName="content"> Your Content here... </div></div>
      )
  }
}

Note: Define id on tags so if you navigate to other page, older meta tags will be replaced/update by new ones.

Step 3 - ReactTitle Component:

If you just want to add title on a page you can use ReactTitle instead.

importReactfrom'react';
import {ReactTitle} from'react-meta-tags';

classComponent2extendsReact.Component {
  render() {
    return (
        <divclassName="wrapper"><ReactTitletitle="Your Page 2"/><divclassName="content"> Your Page 2 Content </div></div>
      )
  }
}

The Server Usage Example:

importMetaTagsServerfrom'react-meta-tags/server';
import {MetaTagsContext} from'react-meta-tags';

/* Import other required modules *//*  some serve specific code */

app.use((req, res) => {
  //make sure you get a new metatags instance for each requestconst metaTagsInstance = MetaTagsServer();

  //react router matchmatch({
    routes, location: req.url
  }, (error, redirectLocation, renderProps) => {
    let reactString;

    try{
      reactString = ReactDomServer.renderToString(
      <Providerstore={store}> 
      {/*** If you are using redux ***/}
      {/* You have to pass extract method through MetaTagsContext so it can catch meta tags */}

        <MetaTagsContextextract = {metaTagsInstance.extract}><RouterContext {...renderProps}/></MetaTagsContext></Provider>
      );
    }
    catch(e){
      res.status(500).send(e.stack);
      return;
    }

    //get all title and metatags as stringconst meta = metaTagsInstance.renderToString();

    //append metatag string to your layoutconst htmlStr = (`
      <!doctype html>
      <html lang="en-us">
        <head>
          <meta charSet="utf-8"/>
          ${meta}
        </head>
        <body>
          <div id="content">
            ${reactString}
          </div>
        </body>
      </html>  
    `);

    res.status(200).send(layout);
  });
});

As per the above code we have to do following for server rendering options

  1. Import MetaTagsServer form server
  2. Import MetaTagsContext form server
  3. Create a new instance of MetaTagsServer
  4. Wrap your component inside MetaTagsContext and pass extract method as props
  5. Extract Meta string using renderToString of MetaTagsServer instance
  6. Append Meta string to your html template.

JSX Layout:

You might also be using React to define your layout, in which case you can use getTags method from metaTagsInstance. The layout part of above server side example will look like this.

//get all title and metatags as React elementsconst metaTags = metaTagsInstance.getTags();

//append metatag string to your layoutconst layout = (
  <htmllang="en-us"><head><metacharSet="utf-8"/>
      {metaTags}
    </head><body><divid="app"dangerouslySetInnerHTML={{__html:reactString}} /></body></html>  
);

const htmlStr = ReactDomServer.renderToString(layout);

res.status(200).send(htmlStr);

Post a Comment for "How Can I Add Meta Tags For Sharing A Particular Link In React.js?"