Im trying to 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 i have 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, my problem is this 'className' which is a little complicated to convert to styled component, any ideas ?
english is not my mother language so could be mistaked
my code:
import React from 'react'
import "./InfoBox.css"
import { Card } from "@material-ui/core"
function InfoBox({ isRed, active, activetored, ...props }) {
return (
<Card onClick={props.onClick}
className={`infoBox ${active && "infoBox--selected"}
${activetored && "infoBox--selectedtored"}
${isRed && "infoBox--red"} `} >
</Card>
)
}
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;
}
CodePudding user response:
For conditional class names I suggest using classnames import: https://www.npmjs.com/package/classnames
The syntax is really easy to read and you can create however complex classnames with it. In your case the code could be something like this:
import classNames from 'classnames';
....
className={classNames('infoBox', {
'infoBox--selected': active,
'infoBox--selectedtored': activetored,
'infoBox--red': isRed
})}
CodePudding user response:
Since it wasn't clear at first, here's a solution if you're using CSS modules instead:
First, import the actual styles from your CSS file:
import * as styles from "./InfoBox.css"
Then you can refer to the available classes in className, like this:
className={styles['infoBox'] `${active && styles['infoBox--selected']`}
