Re-utilizing React Native styles with Styled Components
Having to refactor some components to use styled-components I felt the urge to reuse some existing styles created to be used with React Native StyleSheet, directly on styled!
Let’s assume that:
- You are migrating a React Native app to use Styled Components.
- You have a
Stylesobject somewhere on your code base with all your common styles, that looks something like this:
// ...
export const Styles = {
inputSmall: {
fontSize: 14,
color: Colors.inputColor,
},
// ...
}- You have a component that uses that
Stylesobject:
// ...
const Component = () => {
return (
<View>
{/* ...other components */}
<TextInput style={[Styles.inputSmall, styles.input]} />
</View>
)
}
export default Component
const styles = StyleSheet.create({
input: {
fontSize: 16,
},
})In case you don’t know, Styled Components allows for object interpolation directly in the styles declaration, so when migrating that component to use styled, it can be simplified like so:
// ...
const Input = styled.TextInput`
${Styles.inputSmall};
font-size: 16;
`
const Component = () => {
return (
<View>
{/* ...other components */}
<Input />
</View>
)
}
export default ComponentThanks to Gabriel Rubens for the tip!
…