Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

styled-components - how to set styles on html or body tag?

Ordinarily, when using pure CSS, I have a style sheet that contains:

html {     height: 100%; }  body {     font-size: 14px; } 

When using styled-components in my React project, how do I set styles for the html or body tags? Do I maintain a separate CSS file just for this purpose?

like image 635
JoeTidee Avatar asked Oct 15 '17 23:10

JoeTidee


People also ask

How do you style styled-components?

styled-components utilises tagged template literals to style your components. It removes the mapping between components and styles. This means that when you're defining your styles, you're actually creating a normal React component, that has your styles attached to it.

How can you apply dynamic styles to styled-components?

One way to dynamically change css properties with styled components is to insert a custom prop into your React component and access said property using the dollar sign and curly braces commonly used for template literals. Our current example is testing to see if our use pointer prop is true.


2 Answers

You can, of course, maintain a separate CSS file that you include in your HTML via a <link> tag.

For v4:

Use createGlobalStyle from Styled-components.

import { createGlobalStyle } from 'styled-components'  const GlobalStyle = createGlobalStyle`   body {     color: ${props => (props.whiteColor ? 'white' : 'black')};   } `  <React.Fragment>   <GlobalStyle whiteColor />   <Navigation /> {/* example of other top-level stuff */} </React.Fragment> 

Pre v4:

Styled-components also exports an injectGlobal helper to inject global CSS from JavaScript:

import { injectGlobal } from 'styled-components';  injectGlobal`   html {     height: 100%;     width: 100%;   } ` 

See the API documentation for more information!

like image 140
mxstbr Avatar answered Sep 21 '22 08:09

mxstbr


As of Oct, 2018.

NOTE

The injectGlobal API was removed and replaced by createGlobalStyle in styled-components v4.

According to docs createGlobalStyle is

A helper function to generate a special StyledComponent that handles global styles. Normally, styled components are automatically scoped to a local CSS class and therefore isolated from other components. In the case of createGlobalStyle, this limitation is removed and things like CSS resets or base stylesheets can be applied.

Example

import { createGlobalStyle } from 'styled-components'  const GlobalStyle = createGlobalStyle`   body {     color: ${props => (props.whiteColor ? 'white' : 'black')};   } `  // later in your app  <React.Fragment>   <Navigation /> {/* example of other top-level stuff */}   <GlobalStyle whiteColor /> </React.Fragment> 

Read more on official docs.

like image 33
Madan Bhandari Avatar answered Sep 20 '22 08:09

Madan Bhandari