kodyl / react-document-meta

HTML meta tags for React-based apps. Works for both client- and server-side rendering, and has a strict but flexible API.
MIT License
321 stars 23 forks source link

DocumentMeta renders previous request data #12

Closed leticia closed 8 years ago

leticia commented 8 years ago

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?

danieljuhl commented 8 years ago

When you use server side renderinger, you have to "extract" the content after you render on the server, and then inject the extracted data into you final HTML before serving to the client. The content in react-document-meta is generated when React renders the components.

I'm working on some core changes, and I will create a small example of server-side rendering, but it will probably not come out before end of next week (will see if I can speed things up).

danieljuhl commented 8 years ago

It's your lucky day. I'll commit a server-side rendering example in a few hours - just cleaning up.

Update: see code in example/server-side

leticia commented 8 years ago

Thank you, @danieljuhl!

nicolasiensen commented 8 years ago

Hey @danieljuhl, what if my HTML is being rendered by a React component like this?

danieljuhl commented 8 years ago

@nicolasiensen simply call React.renderToString and assign to a variable before returning the HTML.

  render() {
    const {assets, component, store} = this.props
    const content = React.renderToString(component);
    return (
      <html lang="en-us">
        <head>
          <meta charSet="utf-8"/>
          {DocumentMeta.renderAsReact()}
          <link rel="shortcut icon" href="/favicon.ico" />

          {/* styles (will be present only in production with webpack extract text plugin) */}
          {Object.keys(assets.styles).map((style, i) =>
            <link href={assets.styles[style]} key={i} media="screen, projection"
                  rel="stylesheet" type="text/css"/>
          )}
          <script dangerouslySetInnerHTML={{__html: analytics}} />
        </head>
        <body>
          <div id="content" dangerouslySetInnerHTML={{__html: content}}/>
          <script src="/wysihtml/wysihtml-toolbar.min.js" />
          <script src="/wysihtml/advanced_and_extended.js" />
          <script dangerouslySetInnerHTML={{__html: `window.__data=${serialize(store.getState())};`}} />
          <script src={assets.javascript.main}/>
        </body>
      </html>
    )
  }
nicolasiensen commented 8 years ago

Clever!