export enum SizeEnum {
Small,
Large
}
export interface ICheckbox {
Size: SizeEnum;
}
const Box = styled.div`
height: 20px;
width: 20px;
`
In the above code I want to be able to conditionally change the height and width value of <Box>
based on the prop. How do I do this?
See Logical Operators
and Adapting based on props
for more info.
// Box.
const Box = styled.div`
height: ${({Size}) =>
Size === 'Small' && '25px' ||
Size === 'Large' && '100px' ||
'50px'
};
width: ${({Size}) =>
Size === 'Small' && '25px' ||
Size === 'Large' && '100px' ||
'50px'
};
`
// Render.
<Box/> // 50px - Normal.
<Box Size="Small"/> // 25px - Small.
<Box Size="Large"/> // 100px - Large.
Another way to do this, if you want to add several css styles.
const Box = styled.div`
height:100px;
width:100px;
${props => props.Size === 'Small' && css`
height:20px;
width:20px;
`}
`
You can use the ternary operator
const Box = styled.div`
height: ${props => props.Size === 'Small' ? '20px' : '40px'}
width: ${props => props.Size === 'Small' ? '20px' : '40px'}
`
You can use the elvis operator in something like this:
${(props) => props.someValue ? css` width: 20px;` : css` width: 100px; `}
Hope this helps someone looking into how to use logical operators in React styled components .
We can add the if-checks just like jsx
const Box = styled.div`
height:100px;
width:100px;
${props => props.Size === 'Small' && `
height:20px;
width:20px;
`}
`
Note: No need to include the word css
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.