I am using gatsby-plugin-emotion and want to use values of a components props for styling. This works when using the { css } style syntax inside the jsx, but not when creating a styled component.
This works:
import React from "react";
import { css } from 'react-emotion';
export default props =>
<div className={css`
color: ${props.color};
`}>
my color: {props.color}
</div>
This does not work:
import React from "react";
import styled from 'react-emotion';
const Test = styled('div')`
color: ${props => props.color};
`
export default props =>
<Test>
my color: {props.color}
</Test>
When I do console.log inside the styled div, the prop comes back as undefined and no styles are applied. It does render correctly inside the JSX.
System:
OS: macOS High Sierra 10.13.5
CPU: x64 Intel(R) Core(TM) i5-4278U CPU @ 2.60GHz
Shell: 3.2.57 - /bin/bash
Binaries:
Node: 10.1.0 - /usr/local/bin/node
Yarn: 1.6.0 - /usr/local/bin/yarn
npm: 6.1.0 - /usr/local/bin/npm
Browsers:
Chrome: 67.0.3396.87
Firefox: 51.0.1
Safari: 11.1.1
npmPackages:
gatsby: ^1.9.272 => 1.9.272
gatsby-image: ^1.0.54 => 1.0.54
gatsby-link: ^1.6.40 => 1.6.40
gatsby-plugin-emotion: ^1.1.17 => 1.1.17
gatsby-plugin-sharp: ^1.6.48 => 1.6.48
gatsby-plugin-typography: ^1.7.19 => 1.7.19
gatsby-source-filesystem: ^1.5.39 => 1.5.39
gatsby-transformer-remark: ^1.7.44 => 1.7.44
gatsby-transformer-sharp: ^1.6.27 => 1.6.27
npmGlobalPackages:
gatsby-cli: 1.1.58
gatsby-config.js:
module.exports = {
plugins: [
`gatsby-plugin-emotion`,
`gatsby-transformer-remark`,
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/src/data/posts`,
name: `posts`,
},
},
],
};
I think this should be something like this
import React from "react";
import styled from 'react-emotion';
const Test = styled('div')`
color: ${props => props.color};`
export default props =>
<Test color={props.color}>
my color: {props.color}
</Test>
I had the same issue with styled-components, who's very similar
More documents here : https://emotion.sh/docs/styled#object-styles
@victorDecroix, it does work when you do it like that but that is actually not how it is documented in emotion: https://emotion.sh/docs/styled
It also seems superfluous, so I am leaving this open as a bug for now. Hopefully somebody can explain why I have to pass a property to itself inside a "styled component".
As far as I know this as expected behaviour, and it does makes sense.
Test in your case is a component (a styled one but still a component) that needs props passed if it wants to use them.
Docs: https://emotion.sh/docs/styled#changing-based-on-props
I agree with the previous speakers as it鈥榮 supposed to be used like they mentioned and hence it鈥榮 not a bug.