babel-plugin-styled-components icon indicating copy to clipboard operation
babel-plugin-styled-components copied to clipboard

css props does not work when the component come from a props

Open kopax opened this issue 6 years ago • 3 comments

css does not work

I have the following app with a non ejected create react app:

import { Fragment, PureComponent } from 'react';
import { withTheme } from 'styled-components';
import { css } from 'styled-components';
import H5 from '@bootstrap-styled/v4/lib/H5';
import Ul from '@bootstrap-styled/v4/lib/Ul';
import Li from '@bootstrap-styled/v4/lib/Li';
import React from 'react';

class ServiceItem extends PureComponent {
  render() {
    const { icon: Icon, list, title } = this.props;
    return (
      <div>
        {<Icon className="w-25" css={css`${(props) => `fill: ${props.theme['$brand-primary']};`}`} />}
        <H5>{title}</H5>
        {list.length > 0 && (<Ul>{list.map((item) => <Li key={item}>{item}</Li>)}</Ul>)}
      </div>
    );
  }
}

export default withTheme(ServiceItem);

Expect

To have a valid synthax

Result

×
ReferenceError: Icon is not defined
Module../src/containers/HomePage/components/ServicesAndSolutions/ServiceItem.js
src/containers/HomePage/components/ServicesAndSolutions/ServiceItem.js:14
  11 | const { icon: Icon, list, title } = this.props;
  12 | return (
  13 |   <div>
> 14 |     {Icon && <Icon className="w-25" css={css`${(props) => `fill: ${props.theme['$brand-primary']};`}`} />}
     | ^  15 |     <H5>{title}</H5>
  16 |     {list.length > 0 && (<Ul>{list.map((item) => <Li key={item}>{item}</Li>)}</Ul>)}
  17 |   </div>

Even if the class is not instanciated anywhere in the code, it will crash.

  • As soon as the css props is removed, it can build again.
  • I can set the css props on the <div> and it will work, is it because css cannot work with props?

Versions

  • styled-components: 4.1.3
  • babel-plugin-styled-components: 1.10.0

kopax avatar Dec 22 '18 07:12 kopax

Beside that, I have a question regarding css props.

I am using css={csscolor: red;} and not css={'color: red;}, every where in my code, while in the documentation they do not say to use it.

I thought it was supposed to be used, I've seen that when the css props was released in some source code.

What is the css util for then? I can notice that without it, my IDE (IntelliJ) lose the synthax coloration.

kopax avatar Dec 22 '18 10:12 kopax

#202

satya164 avatar Jan 08 '19 21:01 satya164

Because of how the css prop transpiler works I don't think we'll ever be able to support this. The css prop dynamically generates a new component, which is injected into the global scope. Up there the prop isn't available as a variable so that's why you're seeing the error.

The only way we could support this is to create a new component inside the local component scope which means it'd get recreated over and over on render, which is pretty bad for performance.

quantizor avatar Jun 27 '19 06:06 quantizor