简体   繁体   中英

Problem with using Emotion with Gatsby.js

I am following this tutorial of Gatsby about using Emotion. https://www.gatsbyjs.org/docs/recipes/styling-css#using-emotion

I installed the Emotion using npm install --save gatsby-plugin-emotion @emotion/core @emotion/styled and set up my gatsby-config.js file like this


module.exports = {
  plugins: [`gatsby-plugin-emotion`],
}

But when I was using it like the tutorial did, I encountered a problem where the inline-css of the component is [object Object]

My component looks like this

import React from "react"
import { css } from "@emotion/core"

export default ({ children }) => (
  <main
    css={{
      backgroundColor: "red",
    }}
  >
    {children}
  </main>
)

and I tried to rewrite using a different approach

import React from "react"
import { css } from "@emotion/core"

export default ({ children }) => (
  <main
    css={css`
      background-color: red;
    `}
  >
    {children}
  </main>
)

this time the inline-css of the component is a paragraph

You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop). 

have no ideas why these two approach didn't work

This worked for me (without thorough understanding):

Approach 01

Replace this:

import React from "react"
import { css } from "@emotion/core"

with this:

/** @jsx jsx */
import { css, jsx } from "@emotion/core"

Approach 02

Update gatsby-config.js to contain the plugin gatsby-plugin-emotion :

module.exports = {
  plugins: [
    `gatsby-plugin-emotion`,
  ],
}

This needs a restart of the gatsby development process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM