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;
}
To start, please see here how to use props with styled-components. With those props you can do anything you want inside a styled component and you can achieve this in your code like so:
import React from 'react'
import "./InfoBox.css"
import { Card } from "@material-ui/core"
import styled from 'styled-components'
const StyledCard = styled(Card)`
border-top: ${({$active, $activetored}) => $active ? '10px solid greenyellow' : $activetored && '10px solid red'};
border-color: ${({$isRed}) => $isRed && 'darkblue'};
`
function InfoBox({ isRed, active, activetored, ...props }) {
return (
<StyledCard $isRed={isRed} $active={active} $activetored={activetored} onClick={props.onClick}>
</StyledCard>
)
}
export default InfoBox
Please notice that active and activetored may override each other depends on your order of ternary condition if both are true. Your example does not show such a case were both props are set to true so it should be okay.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With