Limenius / ReactRenderer

Client and Server-side React rendering from PHP
MIT License
237 stars 37 forks source link

Styled-components #17

Closed loiclouvet closed 6 years ago

loiclouvet commented 6 years ago

Hi everyone ! Did anyone successfully make it work with Styled-components using server-side rendering ? (e.g: https://www.styled-components.com/docs/advanced#server-side-rendering).

loiclouvet commented 6 years ago

I've managed to do it in a hacky way, if someone is interested, just comment here :)

georgii-ivanov commented 5 years ago

Me interested... @loiclouvet could you share your solution?

loiclouvet commented 5 years ago

@georgii-ivanov Sorry, was on holidays. I don't own the source anymore :(, maybe @LoicGoyet can help you... As far as I remember, It was only about configuration !

LoicGoyet commented 5 years ago

@georgii-ivanov Hello, sorry for the late late answer :( On the first hand what we did is a HOC like this :

const ServerRendering = Component => {
  const ServerRenderingComponent = props => {
    const styleTags = () => {
      const sheet = new ServerStyleSheet();
      renderToString(sheet.collectStyles(<WrappedComponent {...this.props} />));
      return sheet.getStyleTags();
    }

    return (
      <React.Fragment>
        <style>{styleTags()}</style>
        <Component {...props} />
      </React.Fragment>
    );
  }

  ServerRenderingComponent.displayName = `ServerRenderingComponent(${Component.displayName || Component.name})`;

  return ServerRenderingComponent;
};

// Then export the component you want to render in SSR like this
export default ServerRendering(MyComponent)

Today we got a more custom way to handle it, really specific to our technical stack (which is weird). HOC should still work, but a more elegant way with react hooks.