Autoplay

    Style the body element with styled-components and "injectGlobal"

    Simon VrachliotisSimon Vrachliotis

    In this lesson, we see how we can apply styles globally with the "injectGlobal" helper method in styled-components. This method allows us to apply styles on the body element, which cannot be wrapped in a styled-component.

    reactReact
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 Here is a simple React app that works with styled components. We've got three styled components here which I used to output a Person component. We're currently loading some CSS from App.css file.

    00:15 If I command the import App, you can see the font and margins all messed up, because the styles are targeting the body element. We can't really wrap this in a styled component directly.

    00:25 I'll also import injectGlobal from styled components. I can then, here, type injectGlobal with back-ticks and paste my CSS in there. Here we go. We're back.

    00:40 I can now completely remove the App.css import and all our CSS is being handled by styled components. The Global style have been injected in the styled tag in the document head.

    Discuss

    Discuss