walee
walee

Reputation: 615

conditional className convert to styled component

Im trying to learn and convert my project from css to styled component(https://styled-components.com/), at the moment i have converted all my other components except one component where i am stuck, checked others examples from stackoverflow but it was not same kind. I have conditional class names

My question is how to convert InfoBox component to use styled component ? do i need to inject the styles through some kind of styled-component wrapper or thats not needed ?

english is not my mother language so could be mistaked

my code:

import React from 'react'
import "./InfoBox.css"

function InfoBox({ isRed, active, activetored, ...props }) {
    return (
        <div onClick={props.onClick}
            className={`infoBox ${active && "infoBox--selected"} 
            ${activetored && "infoBox--selectedtored"}
            ${isRed && "infoBox--red"} `} >
           
        </div>
    )
}

export default InfoBox

<div className="app__stats">
          <InfoBox
            isRed
            active={typeofCase === "cases"}
            onClick={(e) => setTypeofCase('cases')}
           
          />
          <InfoBox
            isGreen
            active={typeofCase === "recovered"}
            onClick={(e) => setTypeofCase('recovered')}
         
          />
          <InfoBox
            isRed
            activetored={typeofCase === "deaths"}
            onClick={(e) => setTypeofCase('deaths')}
           
          />
        </div>

css is like this (you can put whatever):

 . infoBox--selected {
  border-top: 10px solid greenyellow;
  }

  . infoBox--selectedtored {
  border-top: 10px solid red;
  }

  . infoBox--red {
  border-color: darkblue;
  }

Upvotes: 0

Views: 1590

Answers (1)

GiL Itzhaky
GiL Itzhaky

Reputation: 304

One of the ideas behind styled-component is to avoid classnames. Instead of setting the css by class, you have few options. the easiest one will probably be to use your props inside the css code, and change the style by it:

const InfoBox = styeld.div`
  border-color: ${props => props.isRed ? 'darkblue' : 'black'};
  border-top: ${props => props.active ? '10px solid greenyellow' : 'red'};
  ...
`;

this way, you don't need classnames (although it can be done with it too, obviously).

Now, instead of the div inside the component, use the InfoBox styled component we just wrote and you good to go.

Upvotes: 1

Related Questions