HTML meta tags for React-based apps. Works for both client- and server-side rendering, and has a strict but flexible API.

Overview

React Document Meta Build Status Coverage Status npm version

HTML meta tags for React-based apps. Works for both client- and server-side rendering, and has a strict but flexible API.

Built with React Side Effect


Installation

npm install --save react-document-meta

Note: React Side Effect requires React 0.14+ - and so does React Document Meta.

Using with React v0.13

Due to several deprecations and breaking changes to React, you'll have to use [email protected]^1.0.0.

Upgrading from 0.1.x to 1.x

As React Side Effect has been upgraded there is a few breaking changes, which is found in the changelog.

Features

  • Supports extending and nesting on any number of levels
  • Ability to auto generate some meta tags for open graph, twitter, and more

Usage

See example folder for a working sample.

import React from 'react';
import DocumentMeta from 'react-document-meta';

class Example extends React.Component {
  render() {
    const meta = {
      title: 'Some Meta Title',
      description: 'I am a description, and I can create multiple tags',
      canonical: 'http://example.com/path/to/page',
      meta: {
        charset: 'utf-8',
        name: {
          keywords: 'react,meta,document,html,tags'
        }
      }
    };

    return (
      <DocumentMeta {...meta}>
        <h1>Hello World!</h1>
      </DocumentMeta>
    );
  }
}

React.render(<Example />, document.getElementById('root'));

Nesting

In most real world use cases, you would like to set some defaults and modify, replace or add just some of the meta tags. react-document-meta always use the deepest data set, but you can add an extend attribute (<DocumentMeta {...metaData} extend />), to instruct the component to merge with the meta data specified one level up. You can add the extend attribute to as many DocumentMeta components you would like, but the chain needs to be complete.

Automatic Meta Tags

react-document-meta has the ability to generate meta tags based on the already provided meta data. Currently only open graph title, description and url is supported, which uses the data from title, description and canonical, and only in the case where the values has not been explicit set for og:title, og:description or og:url respectively.

Server Usage

When using react-document-meta in a project with server-side rendering, you would like to have the final meta data chunk available in your HTML output. You can achieve this by calling DocumentMeta.rewind().

Instead of getting a plain object, you can have the module return the meta as either React components or a HTML string. This is achieved by calling DocumentMeta.renderAsReact() or DocumentMeta.renderAsHTML().

import React from 'react';
import DocumentMeta from 'react-document-meta';

export default handler = (...args) => {
  ...
  const app = React.renderToString(components);
  const meta = DocumentMeta.renderAsHTML();
  const markup = `
    <html>
      <head>
        ${meta}
      </head>
      <body>
        <div id="app">
          ${app}
        </div>
      </body>
    </html>
  `
  ...
}

TODO:

  • Create full documentation
  • Improve flexibility for custom attributes
Comments
  • Warning: Failed propType: Invalid prop `property` supplied to `DocumentMeta`. Check the render method of `SideEffect(DocumentMeta)`.

    Warning: Failed propType: Invalid prop `property` supplied to `DocumentMeta`. Check the render method of `SideEffect(DocumentMeta)`.

    Hi after upgrade I can see this warning: Warning: Failed propType: Invalid prop property supplied to DocumentMeta. Check the render method of SideEffect(DocumentMeta).

    I am using your component:

    const basicMetadata = {
      title: 'Meetbus - Make your travels more fun',
      description: 'Explore awesome places around the world and meet other travelers',
      meta: {
        name: {
          keywords: 'traveling, exploring, wanderlust, adventure, travel, meetup, new zealand'
        },
        property: {
          'og:site_name': 'meetbus.com',
          'fb:app_id': '341640709299908',
          'fb:admins': [1107946314, 1095566451]
        }
      }
    };
    
      render() {
            <DocumentMeta {...basicMetadata} />
    

    Is there any problem with "property" field?

    opened by seeden 8
  • Doesn't work with new React builds

    Doesn't work with new React builds

    G:\work\cinema [master +0 ~5 -0]> npm install --save [email protected]
    npm WARN package.json [email protected] license should be a valid SPDX license expression
    npm WARN unmet dependency G:\work\cinema\node_modules\react-intl requires [email protected]'>=0.11.2 <1.0.0' but will load
    npm WARN unmet dependency G:\work\cinema\node_modules\react,
    npm WARN unmet dependency which is version 0.14.0-rc1
    npm ERR! Windows_NT 6.3.9600
    npm ERR! argv "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "i
    nstall" "--save" "[email protected]"
    npm ERR! node v0.12.5
    npm ERR! npm  v2.11.2
    npm ERR! code EPEERINVALID
    
    npm ERR! peerinvalid The package react does not satisfy its siblings' peerDependencies requirements!
    npm ERR! peerinvalid Peer [email protected] wants [email protected]>= 0.13.0
    

    A fix I can suggest: remove peerDependencies.

    opened by catamphetamine 7
  • google sees the page without meta tags

    google sees the page without meta tags

    at first glance, everything works well and in the code in the browser you can see meta tags. but when you view the page code there is nothing. and google sees the page without meta tags. I use the module on the product catalog page. all data is transferred. I can see everything in the reaction tools. but Google doesn't see it. after I start using this component, almost all pages are removed from the Google cache. I have "react": "^16.2.0", "react-dom": "^16.2.0", "react-router": "^4.2.0", "react-router-dom": "^4.2.2", "_id": "[email protected]"

    opened by romanown 6
  • Server Rendering: DocumentMeta.renderAsHTML() is not a function

    Server Rendering: DocumentMeta.renderAsHTML() is not a function

    Hi,

    Trying to use this plugin, while i'm applying the server rendering code as described in the provided documentation, i keep getting this error: DocumentMeta.renderAsHTML() is not a function, same when i use renderAsReact().

    Any idea?

    Thanks

    opened by therayess 6
  • DocumentMeta renders previous request data

    DocumentMeta renders previous request data

    Hi!

    I'm using React + Redux + server side rendering and react-document-data to display og tags. When opening two different pages, the second one seems to be rendered with the first page tags.

    I declare docMeta as seen in this example.

    The problem is seen in this gif:

    share

    Initially, both pages are rendered with correct meta tags. When I reload "something" and go to "save-the-whales" tab and reload it, meta tags from "something" are displayed.

    Is there something I'm missing on setting up react-document-meta?

    opened by leticia 6
  • 1.0 upgrade trouble: clone fail

    1.0 upgrade trouble: clone fail

    When upgrading to 1.0, I've got a problem where DocumentMetaWithSideEffect.peek() is returning undefined here, and JSON.parse() is falling over here.

    All I have to do is change

    {DocumentMeta.rewind({asReact: true})}
    

    to

    {DocumentMeta.renderAsReact()}
    

    Right?

    opened by erikras 6
  • doesn't work with preact-compat

    doesn't work with preact-compat

    Not sure if you're interested in fixing this, but since this module always requires the server-side react-dom (even on the frontend!) it doesn't work with preact (via preact-compat) since preact-compat/server is not a thing.

    Even if you don't care about preact, we should probably fix this to reduce the amount of code going into front-end only builds.

    opened by yocontra 5
  • Add test coverage via babel-istanbul

    Add test coverage via babel-istanbul

    Your readme lists test coverage as a todo, and we're depending on this project in a project I'm working on, so I figured I'd send you a PR with babel-istanbul hooked up :smiley:

    It was actually a bit tricky to get it to play nicely with Make, so you might find the test command somewhat cryptic, but unfortunately this was out of necessity.

    Thank you so much for the awesome work!

    opened by markdalgleish 5
  • Meta tags not changing

    Meta tags not changing

    I plugging in my data into the metaData:

    
        let metaData = {
          title: aTutorial.headline,
          description: aTutorial.description,
          canonical: `https://www.stanleycyang.com${this.props.location.pathname}`,
          meta: {
            charset: 'utf-8',
            name: {
              keywords: keywordStr
            }
          }
        }
    
    ...
    
      return (
        <main>
            <DocumentMeta {...metaData} />
           ...
        </main>
      )
    

    It doesn't change my meta data (description, keywords, etc). Not sure what I'm doing wrong.

    opened by stanleycyang 5
  • Remove 'react' and 'react-dom' from dependencies

    Remove 'react' and 'react-dom' from dependencies

    This package's dependencies is causing npm/yarn to install React(DOM)@0.14. Would suggest either removing them as dependencies or setting peerDependencies that includes >1.0

    opened by necolas 4
  • Social share sites not recognizing meta tags

    Social share sites not recognizing meta tags

    The meta tags are being generated properly in my doc head, but when I run the urls through various debuggers to get the scrape data it doesn't find the meta tags.

    Using Facebook debugger: http://developers.facebook.com/tools/debug Google data testing tool: http://www.google.com/webmasters/tools/richsnippets Twitter card validator: https://dev.twitter.com/docs/cards/validation/validator

    opened by sreahard 4
  • Update react-side-effect to the latest version 2.1.1, please

    Update react-side-effect to the latest version 2.1.1, please

    Could you please update react-side-effect to its latest version, 2.1.1?

    react-side-effect that react-document-meta is using still uses componentDidMount which will cause annoying warning message.

    I saw latest react-side-effect has change it to unsafe_componentDidMount.

    opened by popmanhe 2
  • Get rid on the extra div

    Get rid on the extra div

    There is not really a need for the wrapping div when there are multiple children. Putting these children in a React.Fragment removes the need for the wrapper.

    opened by jhicken 0
  • the meta has already added. But the SNS website don't use the new meta

    the meta has already added. But the SNS website don't use the new meta

    client-side rendering, the head html is:

    <meta property="og:image" content="/favicon.png">
    <meta name="description" content="Spiral, a professional grade crypto currencies exchange for quantitative trading, makes you a smarter trader.The most favored referral program, high performance, high liquidity, high security standard, support for sub-account management.">
    <meta name="twitter:title" content="Spiral Cryptocurrency Exchange">
    <meta name="twitter:description" content="Spiral, a professional grade crypto currencies exchange for quantitative trading, makes you a smarter trader.The most favored referral program, high performance, high liquidity, high security standard, support for sub-account management.">
    <meta name="twitter:image" content="/favicon.png">
    <meta property="twitter:title" content="穩定幣調研報告:USDT將何去何從?" data-rdm="">
    <meta property="twitter:image" content="/research.jpg" data-rdm="">
    <meta property="og:image" content="/research.jpg" data-rdm="">
    

    But the SNS website don not use the new meta tags,it seems that it do not work. Did i do something wrong? How dose it work

    opened by windinging 1
  • Describe idea behind children prop

    Describe idea behind children prop

    Hello,

    In readme and in examples I see that you suggest to put content as children of this component. I wonder what idea is behind this kind of approach instead use it as childless tag? Explanation in readme will be great. I can create PR with it if I get the purpose.

    By the way I want to ask if code in render method can not be just replaced with return {this.props.children} for sake of simplicity and back compatibility?

    opened by maciekmpintive 0
  • Favicon not working when use IE

    Favicon not working when use IE

    The titile is updated but favicon not display when use IE, the meta as follows:

    const meta = {
          title: 'HomePage Title',
          description: 'This is the homepage title',
          link: {
            rel: { icon: '/favicon.ico' },
          },
        };
    
    opened by blling 1
  • Huge dependency

    Huge dependency

    I swapped from react-document-meta to react-helmet, but while doing that I noticed there appears to be something wrong with the dependencies as when I used react-document-meta my uglified production bundle size was 195 kB while after switching to react-helmet the bundle size dropped down to 65 kB. This change is the only change I made between bundles, so there are certainly some dependency issues that should be resolved. I didn't investigate what causes the issue.

    opened by Merri 2
Owner
kodyl
kodyl
Chrome extension to preview and debug your webpage's meta tags for different social platforms like Twitter, Facebook, WhatsApp, LinkedIn etc.

ogmeta Chrome extension to preview and debug your webpage's meta tags for different social platforms like Twitter, Facebook, WhatsApp, LinkedIn etc. E

Vamsi Rao 22 Aug 4, 2022
The easiest way to move your React application to Server-Side Rendering. Handles Side Effects and synchronizes State.

The easiest way to move your React application to Server-Side Rendering. Handles Side Effects and synchronizes State. Table of Contents Articles Featu

Sergey 87 Sep 13, 2022
React ESI: Blazing-fast Server-Side Rendering for React and Next.js

React ESI: Blazing-fast Server-Side Rendering for React and Next.js React ESI is a super powerful cache library for vanilla React and Next.js applicat

Kévin Dunglas 624 Sep 23, 2022
Studies about Software Architeture in React - basics of server-side rendering, state management and code splitting

Studies about Software Architeture in React - basics of server-side rendering, state management and code splitting

Jéssica Félix 2 Mar 23, 2022
Adds server side rendering support to React Relay

Isomorphic React Relay Enables server-side rendering of React Relay containers. If you use react-router-relay you might also become interested in isom

Denis Nedelyaev 246 May 22, 2022
Famework agnostic and GDPR Compliance library to track user actions to Meta Pixel

Famework agnostic and GDPR Compliance library to track user actions to Meta Pixel. This library is a wrapper around Meta Pixel. The library does not depend on any frameworks or libraries, and can therefore be used within React, Vue, Angular and all others JS based applications.

David Øvrelid 4 Sep 26, 2022
Redux bindings for client-side search

redux-search Higher-order Redux library for searching collections of objects. Search algorithms powered by js-worker-search. Check out the live demo a

Brian Vaughn 1.4k Aug 25, 2022
An example using universal client/server routing and data in React with AWS DynamoDB

react-server-routing-example A simple (no compile) example of how to do universal server/browser rendering, routing and data fetching with React and A

Michael Hart 300 Aug 25, 2022
A boiler code generator for electron with react or vue with taildwindcss in both JavaScript & TypeScript

A boiler code generator for electron with react or vue with taildwindcss in both JavaScript & TypeScript

Rajvir Singh 209 Sep 23, 2022
React Backbone Binding that works with React 16

WithBackbone React Higher Order Component which will bind Backbone Data that works with React Fiber (v.16) Why did we make it There are already a coup

Beanworks 2 Mar 19, 2021
React Clone - How React Works: An In-Depth Guide

Как работает React: подробное руководство Привет, друзья! В этой статье я покажу вам, с чего начинается React. Что это означает? Это означает, что мы

Igor Agapov 5 Nov 25, 2021
React-fade: Proof of Concept react fade in/out that just works without any effort

react-fade Proof of Concept react fade in/out that just works without any effort. Inspired by react native layout animations. How it works FadeIn noth

Park June Chul 2 May 17, 2022
⚛ A reCAPTCHA bridge for React that works.

reCAPTCHA for React A reCAPTCHA library for React that works. Looking for React Native version? Install Install the module yarn add react-recaptcha-

Douglas Nassif Roma Junior 13 Mar 4, 2022
Write down a shell command-line to see how it works in details.

shell.how Write down a shell command-line to see how it works in details. Design Stack TypeScript Next.js Tailwind CSS Recoil for state management, it

Minh-Phuc Tran 224 Sep 21, 2022
This application reproduces the effect of the works page of Kirifuda Inc.

This application reproduces the effect of the works page of Kirifuda Inc.

nemutas 34 Aug 10, 2022
Lightweight auth library based on oidc-client for React single page applications (SPA). Support for hooks and higher-order components (HOC).

Lightweight auth library based on oidc-client for React single page applications (SPA). Support for hooks and higher-order components (HOC).

null 151 Sep 29, 2022
Like useRef, but with lifecycle and ref merging support

useLifecycleRef Like useRef, but with lifecycle and ref merging support Quick Look Here is a simplfied demonstration on how easy to use useLifecycleRe

Billy Kwok 1 Jun 10, 2022
a fork version of vitesse-webext, but with react

@aiou/webext-template a fork version of vitesse-webext, but with react A Vite powered WebExtension (Chrome, FireFox, etc.) starter template. Edit on S

ruaaa 11 Aug 22, 2022
The lightweight and flexible Cookie Consent Banner

The lightweight and flexible Cookie Consent Banner

Porsche AG and Subsidiaries 41 Sep 27, 2022