Skip to content

Latest commit

 

History

History

gatsby-styled-components

Twin + Gatsby + Styled Components

TwinTwinGatsbyStyled componentsStyled components

Download this example using degit

npx degit https://github.com/ben-rogerson/twin.examples/gatsby-styled-components folder-name

From within the new folder, run npm install, then npm start to start the dev server.

Table of contents

Getting started

Installation

Install Gatsby

npx gatsby new gatsby-site

Install the dependencies

npm install --save twin.macro tailwindcss styled-components gatsby-plugin-styled-components
Install with Yarn

Install Gatsby

yarn create gatsby-site

Install the dependencies

yarn add twin.macro tailwindcss styled-components gatsby-plugin-styled-components

Add the global styles

Twin uses the same preflight base styles as Tailwind to smooth over cross-browser inconsistencies.

The GlobalStyles import adds these base styles along with some @keyframes for the animation classes and some global css that makes the ring classes and box-shadows work.

As we should only add the GlobalStyles import once in our project, it’s a good idea to put it in a layout file. You can add Twin’s GlobalStyles import in a new file called src/components/Layout.js:

// src/components/Layout.js
import React from 'react'
import { GlobalStyles } from 'twin.macro'

const Layout = ({ children, ...rest }) => (
  <div {...rest}>
    <GlobalStyles />
    {children}
  </div>
)

export default Layout

Then in your pages, wrap your content with the layout:

// src/pages/index.js
import Layout from './../components/Layout'

const App = () => <Layout>{/* ... */}</Layout>

export default App

Add gatsby-plugin-styled-components

In gatsby-config.js register the plugin for styled-components:

// gatsby-config.js
module.exports = {
  plugins: [`gatsby-plugin-styled-components`],
}

Add the twin config

Twin’s config can be added in a couple of different files.

a) Either in babel-plugin-macros.config.js:

// babel-plugin-macros.config.js
module.exports = {
  twin: {
    preset: 'styled-components',
  },
}

b) Or in package.json:

// package.json
"babelMacros": {
  "twin": {
    "preset": "styled-components"
  }
},

Customization

Next steps

Learn how to work with twin

Learn more about styled-components