Skip to content

Get ssr styles as React Element - #736

Merged
geelen merged 1 commit into
styled-components:v2from
oscar-b:v2-ssr-component
Apr 28, 2017
Merged

geelen merged 1 commit into
styled-components:v2from
oscar-b:v2-ssr-component

Conversation

@oscar-b

@oscar-b oscar-b commented Apr 23, 2017 •

Copy link
Copy Markdown
Contributor

Proof of concept, would appreciate comments.

Makes it possible to render {sheet.getStyleElement()} directly in using React. Current ssr solution requires that the extracted styles are injected into the html outside of React, for instance via Express string substitution. This isn't suitable in for example GatsbyJS.

This needs tests, and proper Flow thingies.

With this change, I can do something like this in Gatsby:

class Html extends React.Component {
  render() {
    const helmet = Helmet.renderStatic();

    // 💅
    const sheet = new ServerStyleSheet();
    sheet.collectStyles(this.props.body);

    return (
      <html lang="sv">
        <head>
          <meta charset="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />

          {helmet.title.toComponent()}
          {helmet.meta.toComponent()}
          {helmet.link.toComponent()}
          {helmet.style.toComponent()}

          {sheet.getStyleElement()}

        </head>
        <body>
          <div id="react-mount" dangerouslySetInnerHTML={{ __html: this.props.body }} />

          <script async src={prefixLink(`/bundle.js?t=${BUILD_TIME}`)} />
        </body>
      </html>
    );
  }
}

@mxstbr-bot

mxstbr-bot commented Apr 23, 2017 •

Copy link
Copy Markdown
Fails
🚫 Please include a CHANGELOG entry. You can find it at CHANGELOG.md

Generated by 🚫 dangerJS

kitten
kitten previously requested changes Apr 23, 2017
Comment thread src/models/StyleSheet.js
}

toElement() {
return this.tags.map(tag => tag.toElement())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The elements here will need to have a key. You should be able to just use cloneElement and add it here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm yes but what should I use for keys? this.names.join('') in ServerTag.toElement?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I set the key in toElement() instead.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just use the index, since this will only be used once and is thus static

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm fighting with Flow:

toElement() {
    return this.tags.map((tag, index) => (
      React.cloneElement(
        tag.toElement(),
        { key: index },
      )
    ))
  }

Gives error:
[flow] property `key` of object literal (Property not found in props of React element `style` See also: call of method `cloneElement`)

Seems like Flow doesn't like adding props to existing elements: meta/flow#1606

Any idea how to get around that?

toElement() {
const attributes = {
[SC_ATTR]: this.names.join(' '),
[LOCAL_ATTR]: this.isLocal,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're searching for el.getAttribute(LOCAL_ATTR) === 'true'. I'm not sure whether this works, if React just adds the property shorthand; Can you check please? :)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The result written to file is something like this:

<style type="text/css" data-styled-components="biyTF hdZKtG gqDZGS clHZEQ yOoIr fUPLnt inUVIL fSmkBB kZQtlQ PIsWY fPJRNv jgRNmm TsYdo iZXahJ bDCuCY kUYNDb foZtll cqjtay fjMziR gqhtmN cEnRUY dhfSfb NkGiE hFJQDZ cOZxoD jYtjIs jskQpj fIEXtD isATaW btuKsl dReRJd dhLCfp gESlQT hoNHWU hRbfbz bMefOW cHPONr fFcRsM" data-styled-components-is-local="true">

You mean it wouldn't work if React omits ="true"?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure, I guess it's possible

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure I follow :)

Comment thread src/models/StyleSheet.js Outdated
addComponent(componentId: string): void,
inject(componentId: string, css: string, name: ?string): void,
toHTML(): string,
toElement(): any,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd guess the type here should just be ReactElement or sth

@oscar-b

oscar-b commented Apr 24, 2017 •

Copy link
Copy Markdown
Contributor Author

For certain things, output seem to break.

Example:

.jhjnFP:before {
	content: "";
}

Is output as:

.jhjnFP:before {
	content: &quot;&quot;;
}

Also instead of:

background-image: url(/22d13351d85a31fb85621052174c8493.jpg);

I get:

background-image: url(&#x27;/22d13351d85a31fb85621052174c8493.jpg&#x27;);

Which looks like this when console.log in the template (before Gatsby/React outputs to file:
background-image: url(\'/22d13351d85a31fb85621052174c8493.jpg\');

Gatsby passes this through renderToString as well, as far as I can see: https://github.com/gatsbyjs/gatsby/blob/master/lib/utils/static-entry.js#L40

@KyleAMathews any idea?

@KyleAMathews

Copy link
Copy Markdown

React escapes text automatically. You probably just need to use dangerouslySetInnerHTML.

@oscar-b

oscar-b commented Apr 24, 2017

Copy link
Copy Markdown
Contributor Author

@KyleAMathews Of course, thanks!

@oscar-b

oscar-b commented Apr 24, 2017

Copy link
Copy Markdown
Contributor Author

@philpl Any outstanding issues you want me to look at?

Makes it possible to render `{sheet.getStyleElement()}` directly in <head> using React
@oscar-b oscar-b changed the title WIP: Get ssr as React Element Get ssr as React Element Apr 24, 2017
@oscar-b oscar-b changed the title Get ssr as React Element Get ssr styles as React Element Apr 24, 2017
@kitten

kitten commented Apr 25, 2017

Copy link
Copy Markdown
Member

@oscar-b No, this is looking good :) @geelen will probably want to take a look at the methods' names though

@oscar-b oscar-b mentioned this pull request Apr 28, 2017
12 of 13 tasks
@geelen
geelen dismissed kitten’s stale review April 28, 2017 08:35

Seems like phil is ok with these changes now

@geelen
geelen merged commit 8ddc6f0 into styled-components:v2 Apr 28, 2017
@geelen

geelen commented Apr 28, 2017

Copy link
Copy Markdown
Member

Merged and added a couple of small tweaks, then released as v2.0.0-17 (styled-components@rc). Thanks @oscar-b!

@oscar-b
oscar-b deleted the v2-ssr-component branch April 28, 2017 09:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants