page-contextdeprecated

Set document's title, description and other meta tags, script and link elements in React applications

Usage no npm install needed!

<script type="module">
  import pageContext from 'https://cdn.skypack.dev/page-context';
</script>

README

React Page Context

NPM version NPM downloads Build Status Coverage Status Dependency Status Online Chat

A higher-order React component that allows to set document's title, description and other meta tags, as well as <link> and <script> tags from inside regular React components via context.page context variable.

See the changelog for past and future (planned) changes to the project  |  Join #react-starter-git on Gitter to stay up to date

How to Install

$ npm install page-context --save

Getting Started

  1. Import PageContext types from page-context npm module
  2. Add contextTypes static property to your React component that needs access to document.title and other <head> elements
  3. Use context.page function to manipulate document's <head> section

Here is an example:

components/HomePage.js

import React, { PropTypes} from 'react';

function HomePage(props, { page }) {
  page({
   title: 'My Home Page',
   meta: [{ name: 'description', content: 'Some page description' }]
  });
  return (
    <div>
      <h1>Welcome!</h1>
      <p>This is my personal home page.</p>
    </div>
  );
}

HomePage.contextTypes = { page: PropTypes.func.isRequired };

export default HomePage;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import PageContext from 'page-context';
import HomePage from './components/HomePage';

ReactDOM.render(
  <PageContext>
    <HomePage />
  </PageContext>,
  document.getElementById('root')
);

Server-side Rendering Example

server.js

import express from 'express';
import ReactDOM from 'react-dom/server';
import PageContext from 'page-context';
import HomePage from './components/HomePage';

const app = express();

app.get('/', (req, res) => {
  let page;
  const body = ReactDOM.renderToString(
    <PageContext ref={component => { page = component.page(); }}>
      <HomePage />
    </PageContext>
  );
  res.send(`
    <html>
      <head><title>${page.title}</title></head>
      <body><div id="root">${body}</div></body>
    </html>
  `)
});

app.listen(3000);

Backers

♥ React Page Context? Help us keep it alive by donating funds to cover project expenses via Patreon or PayPal!

Related Projects

Get in Touch

License

Copyright © 2016 Kriasoft, LLC. This source code is licensed under the MIT license found in the LICENSE.txt file. The documentation to the project is licensed under the CC BY-SA 4.0 license.


Made with ♥ by Konstantin Tarkus (@koistya) and contributors