if statement inside styled component
22,052
Solution 1
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;
`}
`
Solution 2
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.
Solution 3
You can use the ternary operator
const Box = styled.div`
height: ${props => props.Size === 'Small' ? '20px' : '40px'}
width: ${props => props.Size === 'Small' ? '20px' : '40px'}
`
Reference: https://www.styled-components.com/docs/basics
Solution 4
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.
Solution 5
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
Author by
blankface
Updated on July 28, 2022Comments
-
blankface almost 2 years
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? -
blankface about 6 yearswhen i do that i get a typescript error
[ts] Property 'Size' does not exist on type 'ThemedStyledProps<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, any>'.
-
blankface about 6 yearsThrows error in TypeScript
[ts] Property 'Size' does not exist on type 'ThemedStyledProps<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, any>'
-
Amit Kumar about 6 yearsI don't know much about typescript but you can try by changing attribute name size --> deviceSize/ device-size
-
Arman Charan about 6 yearsThat's a
TypeScript
issue. This link might help. -
alvescleiton over 4 yearsZeroDarkThirty, to solve this you should create an prop interface. interface Props { Size: string } and you should use on element const Box = styled.div<Props>` height: ${props => props.Size === 'Small' ? '20px' : '40px'} width: ${props => props.Size === 'Small' ? '20px' : '40px'} `
-
AveryFreeman almost 4 yearsThese are all good answers, I wanted to give you a vote since there's no best way to do this as far as the three examples I see here
-
T04435 about 3 yearsYou want the css`` for syntax highlight :|
-
Naveen DA about 3 yearsIn the official docs, they are not mentioning the css``. styled-components.com/docs/basics#adapting-based-on-props