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.
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
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>,
)
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"
}
},
// .babelrc
// In .babelrc
{
"plugins": [
"babel-plugin-macros",
"babel-plugin-styled-components",
"@babel/plugin-transform-react-jsx",
]
}
Learn how to work with twin
- The prop styling guide - A must-read guide to level up on prop styling
- The styled component guide - A must-read guide on getting productive with styled-components
Learn more about styled-components