如何添加元标记以共享React.js中的特定链接? [英] How can I add meta tags for sharing a particular link in React.js?

查看:155
本文介绍了如何添加元标记以共享React.js中的特定链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有一个使用React.js构建的网上商店应用程序,我想使用HTML元标记自定义在社交媒体上共享的URL的外观(例如,添加说明和图片).此外,我希望特定产品(例如https://www.mywebsite.com/product/<productId>)的路线预览合适的图片及其说明,因此仅在index.html中包含meta标签是不可接受的. /p>

我尝试使用react-helmet和其他用于添加元标记的软件包,但它们没有帮助.我猜是因为react-helmet在应用程序渲染后而不是仅在某个位置共享URL时才添加meta标签.

使用服务器端渲染是解决此问题的唯一方法,还是有一种仅从前端处理它的方法?

解决方案

按照下面的示例逐步进行操作

步骤1 –使用NPM安装以下命令

npm install react-meta-tags --save

注意:您也可以使用反应头盔(第三方库)

第2步–在类组件"中使用MetaTag组件

import React from 'react';
import MetaTags from 'react-meta-tags';

class Component1 extends React.Component {
  render() {
    return (
        <div className="wrapper">
          <MetaTags>
            <title>Your Page 1</title>
            <meta name="description" content="Your description here.." />
            <meta property="og:title" content="Your App" />
            <meta property="og:image" content="Your path/to/image.jpg" />
          </MetaTags>
          <div className="content"> Your Content here... </div>
        </div>
      )
  }
}

注意:在标签上定义ID,这样,如果您导航到其他页面,则旧的元标签将被新的标签替换/更新.

第3步-ReactTitle组件:

如果只想在页面上添加标题,则可以使用ReactTitle.

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

class Component2 extends React.Component {
  render() {
    return (
        <div className="wrapper">
          <ReactTitle title="Your Page 2"/>
          <div className="content"> Your Page 2 Content </div>
        </div>
      )
  }
}

服务器使用示例:

import MetaTagsServer from '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 request
  const metaTagsInstance = MetaTagsServer();

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

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

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

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

    //append metatag string to your layout
    const 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);
  });
});

根据上面的代码,我们必须对服务器渲染选项进行以下操作

  1. 导入MetaTagsServer表单服务器
  2. 导入MetaTagsContext表单服务器
  3. 创建MetaTagsServer的新实例
  4. 将您的组件包装到MetaTagsContext中,并通过提取方法作为道具
  5. 使用MetaTagsServer实例的renderToString提取元字符串
  6. 将元字符串附加到您的html模板.

JSX布局:

您可能还使用React来定义布局,在这种情况下,您可以使用metaTagsInstance中的getTags方法.上面的服务器端示例的布局部分将如下所示.

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

//append metatag string to your layout
const layout = (
  <html lang="en-us">
    <head>
      <meta charSet="utf-8"/>
      {metaTags}
    </head>
    <body>
      <div id="app" dangerouslySetInnerHTML={{__html: reactString}} />
    </body>
  </html>  
);

const htmlStr = ReactDomServer.renderToString(layout);

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

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 HTML meta tags. Besides, I want the route of particular product (e.g. https://www.mywebsite.com/product/<productId>) to preview the appropriate picture and description of it, so it is not acceptable to just include the meta tags in the index.html.

I have tried to use react-helmet and other packages that are used for adding meta tags, but they didn't help. I guess, it is because react-helmet adds the meta tags after the app renders and not just when the URL is shared somewhere.

Is the only solution to this problem to use server-side rendering or there is a way to handle it from front-end only?

解决方案

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

import React from 'react';
import MetaTags from 'react-meta-tags';

class Component1 extends React.Component {
  render() {
    return (
        <div className="wrapper">
          <MetaTags>
            <title>Your Page 1</title>
            <meta name="description" content="Your description here.." />
            <meta property="og:title" content="Your App" />
            <meta property="og:image" content="Your path/to/image.jpg" />
          </MetaTags>
          <div className="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.

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

class Component2 extends React.Component {
  render() {
    return (
        <div className="wrapper">
          <ReactTitle title="Your Page 2"/>
          <div className="content"> Your Page 2 Content </div>
        </div>
      )
  }
}

The Server Usage Example:

import MetaTagsServer from '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 request
  const metaTagsInstance = MetaTagsServer();

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

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

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

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

    //append metatag string to your layout
    const 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 elements
const metaTags = metaTagsInstance.getTags();

//append metatag string to your layout
const layout = (
  <html lang="en-us">
    <head>
      <meta charSet="utf-8"/>
      {metaTags}
    </head>
    <body>
      <div id="app" dangerouslySetInnerHTML={{__html: reactString}} />
    </body>
  </html>  
);

const htmlStr = ReactDomServer.renderToString(layout);

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

这篇关于如何添加元标记以共享React.js中的特定链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆