Skip to content

Instantly share code, notes, and snippets.

@gaearon
Last active August 29, 2015 14:07
Show Gist options
  • Save gaearon/8c413b3cb373febe4d3d to your computer and use it in GitHub Desktop.
Save gaearon/8c413b3cb373febe4d3d to your computer and use it in GitHub Desktop.
Declarative document.title for React
// This is declarative document.title for React.
// No more updating document.title in lifecycle hooks and promise handlers!
//
// Usage:
//
// var SomePage = React.createClass({
// render() {
// // Title might depend on state but it's fine with DocumentTitle
// return (
// <DocumentTitle title={this.state.someData && this.state.someData.text}>
// <div>
// Actual page content goes inside and will be untouched
// </div>
// </DocumentTitle>
// );
// }
// });
//
// Note that we may provide a fallback <DocumentTitle /> at the hierarchy root,
// and it will prevail if no other instances of <DocumentTitle /> override it.
/** @jsx React.DOM */
'use strict';
var React = require('react'),
{ Children } = require('react/addons'),
{ PropTypes } = React;
var DocumentTitle = React.createClass({
propTypes: {
title: PropTypes.string
},
getTitle(props) {
var title = props.title || '';
if (!title) {
title = 'Your Website';
} else {
title += ' · Your Website';
}
return title;
},
componentWillMount() {
document.title = this.getTitle(this.props);
},
componentWillReceiveProps(nextProps) {
var title = this.getTitle(nextProps);
if (title !== document.title) {
document.title = title;
}
},
render() {
if (this.props.children) {
return Children.only(this.props.children);
} else {
return null;
}
}
});
module.exports = DocumentTitle;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment