Is it possible to use the spread operator with a styled component in React Native?
I have this component:
JavaScript
x
6
1
const StyledHeaderText = styled.Text`
2
fontFamily: ${props => props.theme.font};
3
fontSize: ${props => props.theme.fontSizeSubtitle};
4
color: ${props => (props.lightMode) ? props.theme.fontColor : props.theme.fontPrimaryColor}
5
`;
6
But lets say that in my theme, I have an object that has both the fontFamily and the fontSize, and I re use all over the app. I would like to be able to know if I can do something like this, which currently it is not working:
JavaScript
1
5
1
const StyledHeaderText = styled.Text`
2
...${props => props.theme.fontHeader};
3
color: ${props => (props.lightMode) ? props.theme.fontColor : props.theme.fontPrimaryColor}
4
`;
5
This would be useful too setting up elevation in iOS for example, since I have to setup 4 styles.
Thanks
Advertisement
Answer
You can use the css helper function to generate the specific css and return it as a template literal.
JavaScript
1
12
12
1
import styled, {css} from 'styled-components/native'
2
3
const GlobalStyles = css`
4
fontFamily: ${props => props.theme.font};
5
fontSize: ${props => props.theme.fontSizeSubtitle};
6
`
7
8
const StyledHeaderText = styled.Text`
9
${GlobalStyles}
10
// Other Styles
11
`
12
or conditionally as
JavaScript
1
5
1
const StyledHeaderText = styled.Text`
2
${props => props.theme.fontHeader ? GlobalStyles : 'fontSize: 14'}
3
// Other Styles
4
`
5