I have this React component with a few properties, and I want styles to apply only if the property has a value, I tried something like this:
export const Text = ({text, color, size, fontFamily}) => {
const StyledParagraph = styled.p`
margin: 0;
font-size: ${props => props.size !== undefined ? props.size : '1.3em'};
`;
const textProps = {
text: [text],
color: [color],
size: [size],
fontFamily: [fontFamily],
}
return (
<StyledParagraph {...textProps}>{text}</StyledParagraph>
)
}
I call it like:
<Text text="some text"/>
I'm not passing the property size
, so I want the font-size
to be the default value I specified (font-size: ${props => props.size !== undefined ? props.size : '1.3em'}
)
However, that's not working. What am I missing here? Thanks in advance.
you have incorrectly defined the value for textProps. By using []
, you have made each property into an array which is why it doesn't work when you try to use it in styled-component
Use it like below
const textProps = {
text: text,
color: color,
size: size,
fontFamily: fontFamily,
}