Skip to content

Latest commit

 

History

History

react-styled-components

Twin + Parcel + Styled Components

TwinTwinParcelStyled componentsStyled components

This example uses Parcel to build a React App styled with Twin + styled-components.

Download this example using degit

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

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

Table of contents

Getting started

Installation

npm install react react-dom styled-components
npm install -D @babel/core @babel/plugin-transform-react-jsx twin.macro tailwindcss babel-plugin-styled-components
Install with Yarn
yarn add react react-dom styled-components
yarn add @babel/core @babel/plugin-transform-react-jsx twin.macro tailwindcss babel-plugin-styled-components -D

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.

You can import GlobalStyles within a new file placed in src/styles/GlobalStyles.js:

// src/styles/GlobalStyles.js
import React from 'react'
import { createGlobalStyle } from 'styled-components'
import tw, { theme, GlobalStyles as BaseStyles } from 'twin.macro'

const CustomStyles = createGlobalStyle({
  body: {
    WebkitTapHighlightColor: theme`colors.purple.500`,
    ...tw`antialiased`,
  },
})

const GlobalStyles = () => (
  <>
    <BaseStyles />
    <CustomStyles />
  </>
)

export default GlobalStyles

Then import the GlobalStyles file in src/index.js:

// src/index.js
import React from 'react'
import { createRoot } from 'react-dom/client'
import GlobalStyles from './styles/GlobalStyles'
import App from './App'

const container = document.getElementById('root')
const root = createRoot(container)
root.render(
  <React.StrictMode>
    <div>
      <GlobalStyles />
      <App />
    </div>
  </React.StrictMode>,
)

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"
  }
},

Add the babel config

// .babelrc
// In .babelrc
{
  "plugins": [
    "babel-plugin-macros",
    "babel-plugin-styled-components",
    "@babel/plugin-transform-react-jsx",
  ]
}

Customization

Next steps

Learn how to work with twin

Learn more about styled-components