We will create different styles to style different components, correct?
And most of them will have duplicate elements, correct?
What are the disadvantages of this problem?
- You will clutter your file with duplicate lines of code.
- It will increase the file size and increase the application size.
- Not very efficient way of coding.
- Limited reusability.
How to fix that?
Example
Here I am going to style two text components and this is my style…
const text1Style = { fontFamily: myFont, marginTop: '15%', textAlign: 'center' fontSize: 28, fontWeight: 'bold' }; const text2Style = { fontFamily: myFont, marginTop: '15%', textAlign: 'center' marginBottom: '20%', fontSize: 20 };
Now what we can do to fix it?
Its simple…create a parent style and inherit from it. Its not hard as it seems…
The above code can be transformed like this.
// Common style for two texts // const parentTextStyle = { fontFamily: myFont, marginTop: '15%', textAlign: 'center' }; const text1Style = { ...parentTextStyle, fontSize: 28, fontWeight: 'bold' }; const text2Style = { ...parentTextStyle, marginBottom: '20%', fontSize: 20 };
In this way you can extend it to any number of components and even across the application by defining it in a styles file.
Render
The render will look like this
render() { return ( <View style={containerStyle}> <Text style={text1Style}> { text1 } </Text> <Text style={text2Style}> { text2 } </Text> </View> );
Much cleaner code. Thats it…
Please leave your valuable comments.