gaearon / react-document-title

Declarative, nested, stateful, isomorphic document.title for React
MIT License
1.86k stars 105 forks source link

As high order component #26

Closed srph closed 8 years ago

srph commented 9 years ago

Initial idea:

@title(props => `${props.user.name}'s page`)
class SomeComponent extends Component {
}

Has its downsides. One obvious example:

// works
class SomeComponent extends Component {
  render() {
    return (
      <DocumentTitle title={`{this.state.user}'s profile`}>
        ..
      </DocumentTitle>
    );
  }
}

// won't work in the proposed api
@title(...)
class SomeComponent extends Component {
  render() {
    return (
      ..
    );
  }
}

But this doesn't happen very happen often, and I don't think it should. See Smart and Dumb Components.

Would send a PR if this is okay.


Awesome work by the way, @gaearon!

gaearon commented 8 years ago

How about we change export to have two named exports: Title (component) and title (HOC)?

srph commented 8 years ago

That's a good idea. But IMO, new people coming to this library could get confused (maybe? :confused:).

gaearon commented 8 years ago

I'll close because I'm fairly satisfied with existing API and I don't want to have two ways to do the same thing.

cooperka commented 6 years ago

Posting my working HOC example because Google sent me to this issue:

import DocumentTitle from 'react-document-title';
import { compose, getDisplayName, setDisplayName } from 'recompose';

// HOC to set the document title from any page.
export function withDocumentTitle(title) {
  return (Component) => {
    const Enhanced = (props) => (
      <DocumentTitle title={title}>
        <Component {...props} />
      </DocumentTitle>
    );

    return compose(
      setDisplayName(getDisplayName(Component)),
    )(Enhanced);
  };
}

Usage:

const WelcomePage = /* ...your component... */;
export default withDocumentTitle('Welcome')(WelcomePage);