Skip to content

Latest commit

 

History

History

cra-emotion

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Twin + Create React App + Emotion

TwinTwinCreate React AppEmotion

Download this example using degit

npx degit https://github.com/ben-rogerson/twin.examples/cra-emotion 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 Create React App

npm init create-react-app my-app

Install the dependencies

npm install twin.macro tailwindcss @emotion/react @emotion/styled
Install with Yarn

Install Create React App

yarn create create-react-app my-app

Install the dependencies

yarn add twin.macro tailwindcss @emotion/react @emotion/styled

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 add Twin’s GlobalStyles import in src/index.js:

// src/index.js
import React from 'react'
import { render } from 'react-dom'
import { GlobalStyles } from 'twin.macro'
import App from './App'

render(
  <>
    <GlobalStyles />
    <App />
  </>,
  document.getElementById('root'),
)

Add the twin config (optional)

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: 'emotion',
  },
}

b) Or in package.json:

// package.json
"babelMacros": {
  "twin": {
    "preset": "emotion"
  }
},

Note: The preset gets set to 'emotion' by default, so adding the config is only useful if you want to adjust Twin’s other options.

Add the jsx pragma

To use the tw and css props, emotion must first extend jsx with a jsx pragma.

When styling with the tw or css prop, add the pragma at the top of your file. This also replaces the react import, unless you’re using fragments <>.

/** @jsxImportSource @emotion/react */
import tw from 'twin.macro'

const Input = () => <input tw="bg-black" />
// or
const Input = () => <input css={tw`bg-black`} />

You can automate the injection of the jsx pragma but you’ll need to use a package like rewire create react app to allow changes to the project .babelrc. Check the twin emotion + react docs for the babel config to use.

Note: After build, if you’re seeing "process is not defined" then npm install and add "babel-plugin-transform-inline-environment-variables" to .babelrc

Customization

Next steps

Learn how to work with twin

Learn more about emotion