how could i pass two props from jsx to scss

12,069

Solution 1

You can't pass props to SCSS, but styled-components supports that. See Adapting based on props from its documentation.

Without styled-components, the only other option is using inline styles by passing a style prop to the element.

Solution 2

You could do this with inline CSS or using a CSS Object in a JS file. But not directly in a file that is interpreted as CSS specifically.

TECHNICALLY, you could achieve this using server side rendering, requiring express to overwrite a file in the file system and return the style. But that's insane, and dumb, and insane.

Share:
12,069

Related videos on Youtube

jose1221
Author by

jose1221

Updated on June 04, 2022

Comments

  • jose1221
    jose1221 almost 2 years

    I have following two props that i need to access in linear-gradient in MyComponent.scss

    startColor: PropTypes.string
    endColor: PropTypes.string
    

    My component looks like below

    MyComponent.jsx
    
    <myComponent 
      {...customProps}
      style={{color: customProps.color }}
      className={classess}
      ...other props here..
      />
    

    Currently it accepts only one color.

    linear-gradient property in MyComponent.scss looks like below

    linear-gradient(to left, currentcolor, currentcolor);
    

    It'll be updated to use startColor and endColor.

    How could i achieve that?

    • Ioan
      Ioan about 6 years
      You can't do that.
    • Tiago Alves
      Tiago Alves about 6 years
      You should use inline styles or some CSS in JS solution like Styled Components
  • Joshua Underwood
    Joshua Underwood about 6 years
    styled-components is a great library. +1
  • Dom
    Dom about 6 years
    Agreed, one of my first additional libraries in pretty much any React project. :)
  • jose1221
    jose1221 about 6 years
    Thanks. Can you please tell me how could i use inline style for both prop?
  • Dom
    Dom about 6 years
    Sure, you could do style={{ background: `linear-gradient(to left, ${props.startColor}, ${props.endColor})` }}
  • jose1221
    jose1221 about 6 years
    I see. The problem is myComponent is a progress bar and this will apply linear gradient to all progress bars and in scss i am not doing linear-gradient to classes having value = 100 (fully loaded progress bars)
  • jose1221
    jose1221 about 6 years
    @DominikJanković so i added this style ` style={{ color: customProps.color, background: linear-gradient(to left, transparent, rgba(255,255,255,.5)), linear-gradient(to left, ${customProps.color}, ${customProps.color}) }}` Not passing startColor and endColor yet. just trying to apply the gradient on same color but it doent apply gradient. Any idea?
  • Dom
    Dom about 6 years
    I'm not sure if you can have multiple linear-gradients defined in the background prop. What are you trying to do? I made a simple CodePen so compare it with what you have: codepen.io/anon/pen/PRzJLP?&editors=0010