• Stars
    star
    226
  • Rank 170,338 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Handle document meta/head tags in isomorphic react with ease.

react-meta-tags

Handle document meta/head tags in isomorphic react with ease.

Handling title and meta/head tags in a isomporhic react is tricky. Its declarative to define those tags within the component, but they need to be moved on document head on client side as well as server side. While there are other modules which helps with the use-case like react-helmet and react-document-meta, but they require to define those tags in a object literal. react-meta-tags allow you to write those tags in a declarative way and in normal jsx format.

Install

Through npm npm install react-meta-tags --save

Or get compiled development and production version from ./dist

Usage

Using MetaTag Component

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

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

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

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="Page 2"/>
          <div className="content"> Some Content </div>
        </div>
      )
  }
}

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);
  });
});

So as per above code we have to do following for server rendering

  1. Import MetaTagsServer and MetaTagsContext
  2. Create a new instance of MetaTagsServer
  3. Wrap your component inside MetaTagsContext and pass extract method as props
  4. Extract meta string using renderToString of MetaTagsServer instance
  5. 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);

Meta Tag Uniqueness

  • The module uniquely identifies meta tag by id / property / name / itemProp attribute.
  • Multiple meta tags with same property / name is valid in html. If you need such case. Define a different id to both so that it can be uniquely differentiate.
  • You should give an id if meta key is different then property/name/itemProp to uniquely identify them.

More Repositories

1

react-number-format

React component to format numbers in an input or as a text.
JavaScript
3,763
star
2

iv-viewer

A zooming and panning plugin inspired by google photos for your web images.
JavaScript
441
star
3

patternLock

A light weight plugin to simulate android like pattern lock interface for your hybrid app or website.
JavaScript
376
star
4

angulargrid

Pinterest like responsive masonry grid system for angular
JavaScript
277
star
5

radialIndicator

A simple and light weight circular indicator / progressbar plugin.
JavaScript
232
star
6

contextMenu.js

contextMenu.js is a plugin to create windows like context menu with keyboard interaction, different type of inputs ,trigger events and much more.
JavaScript
208
star
7

ScrollMenu

A new interface to replace your old boring scrollbar
JavaScript
203
star
8

jsonQ

A JavaScript library to make manipulation and extraction of data from a JSON very easy and fast.
JavaScript
202
star
9

relative-to-alias

πŸ› οΈ A codemod to do large-scale refactor of your relative path imports to alias.
JavaScript
127
star
10

FlakeId

Twittter Snowflake like unique id generator plugin for nodejs and browser
JavaScript
76
star
11

modalBox.js

A very light weight and minimal plugin to display modal window.
JavaScript
43
star
12

patternCaptcha

Android like pattern matching captcha system for your node webapps.
JavaScript
42
star
13

github-turbo-pr

Chrome extension to optimize github for handling big pull request. πŸš€
JavaScript
25
star
14

eventPause.js

eventPause is a tiny plugin with lots of methods to control events. So whenever you want you can pause and activate any event.
JavaScript
21
star
15

create-effect

A small utility to create custom hooks using useEffect
JavaScript
9
star
16

fqueue

A micro-plugin to queue function execution to handle asynchronous flow and stepping through functions.
JavaScript
7
star
17

coequal.js

coequal is a small utility function to check equality of all data types and objects in JavaScript.
JavaScript
6
star
18

node-website-build-script

Boilerplate to use node.js as a build script for web projects.
CSS
4
star
19

LongListScroller

A small plugin to handle long list scroll using IScroll
JavaScript
3
star
20

findR.js

A find and replace JavaScript plugin for webpages.
JavaScript
3
star
21

deferred

A mini deferred plugin, having just what you need
JavaScript
2
star
22

ask-me-anything

A place where you can ask me anything about frontend, architecture, performance or general career stuff
2
star
23

number-format-app

JavaScript
1
star
24

class-to-function-with-react-hooks

Examples to map lifecycle method of a class component to a functional component with react hooks
JavaScript
1
star
25

isomorphic_react_sample

An isomorphic react sample app.
JavaScript
1
star
26

babel-plugin-react-create-element-alias

A babel plugin to replace React.createElement to an alias
JavaScript
1
star
27

patch-commits

Patch all commits to have desired changes in a branch
JavaScript
1
star
28

s-yadav.github.com

HTML
1
star
29

useful-array-prototypes

This repository contains some useful prototypes which native javascript dont provide or have some perfomance gain over native javascript functionality.
JavaScript
1
star