Styling Your React Apps

React Styled Components

Styled Components

Styled Components lets you keep your CSS within scope and provides a lot of benefits like (copied from their Styled Component Docs):

Getting Started

First let's install the package with yarn.

yarn add styled-components

Great, now let's import it and start playing around with it. The styled default export it provides us let's us create normal html tags using tag literals.

 

import React from "react"

import styled, { ThemeProvider } from "styled-components"

const Title = styled.h1` color: blue `

function App() {

return (

<div className="App">

<Title>Hello</Title>

</div> )

}

 

export default App

 

Great, next we'll be extending one component's styles and customizing it a bit.

 

import React from "react"

import styled, { ThemeProvider } from "styled-components"

 

const Title = styled.h1` color: blue ` // Extends Title

const UnderlinedTitle = styled(Title)`

 padding: 20px;

text-decoration:

underline;

 

function App() {

return (

<div className="App">

<Title>Hello</Title>

<UnderlinedTitle>My UnderlinedParagraph</UnderlinedTitle>

</div>

)}

 

export default App `

 

Alright, next -> You can also pass a function for the theme prop. This function will receive the parent theme, that is from another higher up the tree. This way themes themselves can be made contextual.

 

import React from "react"

import styled, { ThemeProvider } from "styled-components"

 

const Title = styled.h1`

color: ${props => props.theme.fg};

font-size: 100px;

margin: 0;

background: ${props => props.theme.bg}; `

// Extends Title

const UnderlinedTitle = styled(Title)`

padding: 20px;

text-decoration: underline; `

 

// Define our `fg` and `bg` on the theme

const theme = { fg: "palevioletred", bg:"red" }

 

function App() {

return (

<div className="App">

<Title>Hello</Title>

<ThemeProvider theme={theme}>

<UnderlinedTitle>My UnderlinedParagraph</UnderlinedTitle>

</ThemeProvider> </div>

) }

 

export default App

 

Looking to get your project off the ground? We can help you with design, development and digital marketing services!

123/10 Pannipitiya Road, Battaramulla, Sri Lanka

info@nugo.xyz

+94 77 38 77 388