Merging two CSS Style objects using Typescript in React Native

I am in the starting phase of using Typescript and I am sharing this code which I created to merge two different CSS definition files to combine and use merged css styles.

I used similar code to combine two javascript objects which held css definitions using simple JSON object and I could use it simply using Object.assign before using StyleSheet.create final css object.

However when using similar approach did not work while using Typescript in my new project. All I had to do is to typecast my new styles using Style type before defining and creating the css object.

Let’s see with help of an example. I hope code is explanatory for someone with prior Reactjs knowledge.

Example: Merging two style objects using Typescript

We have a css styles baseStyle.ts with the following code:

import { StyleSheet, ViewStyle, TextStyle } from "react-native";
type Style = {
  underline: TextStyle,
  textCenter: TextStyle,
  container: ViewStyle,
}
const baseStyle = StyleSheet.create<Style>({
  underline: { 
    textDecorationLine: 'underline' 
  },
  textCenter:{
    textAlign:'center'
  },
  container:{
    alignItems: "center",
    backgroundColor:"white"
  }
})
export default baseStyle

We have another file named loginStyle.ts which returns the a combined style object at the end:

import { StyleSheet, ViewStyle, ImageStyle } from "react-native";
type Style = {
  container: ViewStyle,
  loginContainer: ViewStyle,
  logo: ImageStyle,
}
const defaultStyle = StyleSheet.create<Style>({
  logo: {
    width: moderateScale(182),
    height: moderateScale(60)
  },
  loginContainer:{
    paddingTop: moderateScale(60)
  },
  container:{
    alignItems: "center",
    backgroundColor:"white"
  }
})
import baseStyle from './baseStyle'
export default Object.assign(baseStyle, defaultStyle)

Eventually we use it in our view file login.tsx

Import

import style from '@/assets/style/loginStyle'

And use

<View style={[style.container, style.loginContainer]}>
...
</View>

 

Leave a Reply