I was looking at the code of the new React beta documentation website and I saw this code
const ContainerWrapper = ({children}) => (
<div
css={{ <----------------------------------------------------
backgroundColor: 'hsl(222, 14%, 10%)',
}}>
{children}
</div>
);
I’m curious about how they’re using css attribute here instead of style. Is this a new feature?
2
Answers
That website is built with gatsby and they are using
gatsby-plugin-glamor
plugin. It simply allows you to write CSS in JS inline. You can read more here: https://www.gatsbyjs.com/plugins/gatsby-plugin-glamor/The
css
attribute you’re seeing is actually a feature of Emotion, a CSS-in-JS library that is being used here.Emotion is a library that allows you to write CSS in your JavaScript code, using a syntax that is similar to CSS. The
css
attribute you’re seeing is a way to use Emotion’s CSS-in-JS syntax in React components.When you use the
css
attribute in a React component, you’re actually passing a CSS-in-JS object to Emotion’scss
function. This function takes the CSS-in-JS object and generates the corresponding CSS styles at runtime. Emotion then injects the generated CSS styles into the HTML document.The reason why Emotion uses the
css
attribute instead of the style attribute is to avoid conflicts with the standard style attribute, which is used to define inline styles in React components. By using a different attribute name, Emotion can avoid accidentally overwriting any inline styles that may be defined using the style attribute.