So I was wondering if it is possible to use props in a switch statements in styled components. For example, let's say I have a prop color
and a type
, Ie:
let HeaderCustomizations = { type: String, color: String }
And the following switch statement:
const headerStyle = props => {
switch (props.type) {
case "underline":
return `
padding-bottom: 2px;
border-bottom: 3px solid rgb(134, 38, 60);
`;
case "borderBottom":
return `
width: 100%;
// Why doesn't this work? it does not get rendered properly.
border-bottom: 2px solid ${props => props.color};
`;
}
}
I use this as follows:
export const HeaderStyling = styled('div', HeaderCustomizations)`
display: flex;
align-items: center;
-webkit-box-align: center;
margin-bottom: 0.5em;
${(props) => headerStyle(props)}
`;
In the switch statement I like to use the color prop, Ie:
border-bottom: 2px solid ${props => props.color};
But that does not seem to work. I'm quite new to styled components so I might me missing something obvious...
Anyway, would love to know how I can use props in a switch statement with styled components.
It isn't working because you're setting the border color to a function, not a value. If you were to expand the case where props.type is borderBottom, you'd get:
export const HeaderStyling = styled('div', HeaderCustomizations)`
display: flex;
align-items: center;
-webkit-box-align: center;
margin-bottom: 0.5em;
${(props) => `
width: 100%;
border-bottom: 2px solid ${props => props.color};
`}
`;
The solution is simply to change border-bottom: 2px solid ${props => props.color};
to border-bottom: 2px solid ${props.color};
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.