2

I couldn't figure this out from the documentation.

I'm trying to add some global styles to my server side rendered React application via styled-components - but I can't figure out how to do this.

Here's parts of my globalStyles.js:

import { injectGlobal } from 'styled-components';

export default () => injectGlobal`
    @import url('https://fonts.googleapis.com/css?family=Pacifico');
    @import url('https://fonts.googleapis.com/css?family=Open+Sans:300,400');
    html {
        box-sizing: border-box;
    }
    *, *:before, *:after {
        box-sizing: inherit;
    }
`;

Here's my universally rendering express-handler:

const path = require('path');
const fs = require('fs');

const React = require('react');
const { renderToString } = require('react-dom/server');
const { StaticRouter } = require('react-router-dom');
const { ServerStyleSheet } = require('styled-components');

const { default: App } = require('../src/containers/App');
const baseStyles = require('../src/styles'); // How to get this in the global css

const indexFile = fs.readFileSync(path.resolve(__dirname, '..', 'build', 'index.html'), 'utf8');

function universalLoader(req, res) {
    const css = new ServerStyleSheet();
    const context = {};

    baseStyles();

    // Create the markup from the React application
    const markup = renderToString(
        css.collectStyles(
            <StaticRouter context={context} location={req.url}>
                <App />
            </StaticRouter>
        )
    );

    const html = indexFile
        .replace('{{SSR}}', markup)
        .replace('{{CSS}}', css.getStyleTags());

    // Send the response back to the user
    res.send(html);
};

1 Answer 1

2

Turns out, calling baseStyles() (which in turn is calling injectGlobal) in my <App /> component render() method fixed the problem. :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.