Styling with StyleSheet
1. Creating Styles
Example: Basic StyleSheet Creation
import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f0f0f0',
},
text: {
fontSize: 18,
color: '#333',
},
});
| Property | Value Type | Description |
|---|---|---|
| flex | number |
Controls how much space a component should take up relative to its siblings |
| justifyContent | 'flex-start' | 'flex-end' | 'center' | 'space-between' | 'space-around' | 'space-evenly' |
Aligns items along the main axis |
| alignItems | 'flex-start' | 'flex-end' | 'center' | 'stretch' |
Aligns items along the cross axis |
| backgroundColor | string |
Sets the background color of a component |
| fontSize | number |
Sets the font size of text elements |
| color | string |
Sets the color of text elements |
Note: StyleSheet.create() is used to define styles that are optimized and cached by React Native.
2. Using Inline Styles
Example: Basic inline style usage
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ fontSize: 20, color: 'blue' }}>Hello World</Text>
</View>
| Property | Value Type | Description |
|---|---|---|
| flex | number |
Defines how a component should expand to fill available space |
| fontSize | number |
Sets the size of the font in pixels |
| color | string |
Sets the color of the text (supports hex, named colors) |
| backgroundColor | string |
Sets the background color of the component (supports hex, named colors) |
| margin | number |
Sets the margin around the component in pixels |
| padding | number |
Sets the padding inside the component in pixels |
Note: Inline styles are applied directly to the component and do not support media queries or pseudo-selectors.
3. Combining Multiple Styles
Example: Combining Styles with StyleSheet.flatten
import { StyleSheet, View } from 'react-native';
const baseStyle = StyleSheet.create({
padding: 10,
borderRadius: 5,
});
const dynamicStyle = StyleSheet.create({
backgroundColor: 'blue',
color: 'white',
});
const combinedStyle = StyleSheet.flatten([baseStyle, dynamicStyle]);
// Usage in component
<View style={combinedStyle}>
<Text style={combinedStyle.text}>Styled Text</Text>
</View>
| Property | Description | Usage |
|---|---|---|
| StyleSheet.flatten | Combines multiple style objects into one | StyleSheet.flatten([style1, style2]) |
| style array | Accepts an array of style objects | [style1, style2, ...] |
Note:
StyleSheet.flatten does not merge nested objects. For deep merging, consider using a utility like lodash.merge.
Warning: Styles in the array are applied in order, with later styles overriding earlier ones.
4. Understanding Style Inheritance
Note: React Native's styling system is based on Flexbox and follows a subset of CSS properties. Style inheritance in React Native behaves differently than in web CSS.
| Property | Description | Behavior |
|---|---|---|
| flexDirection | Defines the direction of flex items | Can be inherited by child views if not overridden |
| alignItems | Aligns items along the cross axis | Can be inherited by child views if not overridden |
| justifyContent | Aligns items along the main axis | Can be inherited by child views if not overridden |
| padding | Space inside the component's border | Cannot be inherited; must be explicitly set on each view |
| margin | Space outside the component's border | Cannot be inherited; must be explicitly set on each view |
| backgroundColor | Background color of the component | Cannot be inherited; must be explicitly set on each view |
| color | Text color of the component | Cannot be inherited; must be explicitly set on each view |
Example: Style Inheritance in Flexbox
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
const ParentView = () => {
return (
<View style={[styles.container, { flexDirection: 'column' }]}>
<View style={styles.child}>
<Text style={styles.text}>Child Text</Text>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
child: {
// flex properties are inherited from parent
flex: 1,
},
text: {
// color is NOT inherited, must be set explicitly
color: '#000',
},
});
Key Points About Style Inheritance
- Flexbox properties like
flexDirection,alignItems, andjustifyContentcan be inherited by child views if not overridden. - Layout properties like
padding,margin, andbackgroundColorare NOT inherited and must be explicitly set on each view. - Text properties like
colorare NOT inherited and must be explicitly set on each view.
5. Using Absolute Positioning
| Property | Values | Description |
|---|---|---|
| position | 'absolute' |
Positions the element relative to its nearest positioned ancestor |
| top | number |
Distance from the top edge of the parent container |
| left | number |
Distance from the left edge of the parent container |
| right | number |
Distance from the right edge of the parent container |
| bottom | number |
Distance from the bottom edge of the parent container |
Example: Absolute Positioning
const styles = StyleSheet.create({
container: {
position: 'relative',
width: 300,
height: 300,
},
absoluteBox: {
position: 'absolute',
top: 50,
left: 50,
width: 100,
height: 100,
backgroundColor: 'blue',
}
});
Note: Absolute positioning removes the element from the normal document flow, which can affect layout of siblings.
6. Applying Transforms
| Property | Values | Description |
|---|---|---|
| transform | Array |
Array of transform functions to apply |
| transformMatrix | Array |
Directly set the transform matrix |
| rotate | string |
Rotation in degrees (e.g., '45deg') |
| rotateX | string |
Rotation around X axis in degrees |
| rotateY | string |
Rotation around Y axis in degrees |
| rotateZ | string |
Rotation around Z axis in degrees |
| scale | number |
Scale factor (e.g., 1.5) |
| scaleX | number |
Scale factor along X axis |
| scaleY | number |
Scale factor along Y axis |
| translateX | number |
Translation along X axis in pixels |
| translateY | number |
Translation along Y axis in pixels |
| skewX | string |
Skew along X axis in degrees |
| skewY | string |
Skew along Y axis in degrees |
Example: Applying Rotation and Scale
const styles = StyleSheet.create({
rotatedBox: {
width: 100,
height: 100,
backgroundColor: 'blue',
transform: [
{ rotate: '45deg' },
{ scale: 1.2 }
]
}
});
Example: Using translateX and translateY
const styles = StyleSheet.create({
translatedBox: {
width: 100,
height: 100,
backgroundColor: 'red',
transform: [
{ translateX: 50 },
{ translateY: 30 }
]
}
});
7. Working with Colors
| Property | Values | Description |
|---|---|---|
| backgroundColor | "#FF0000", "red", "rgb(255, 0, 0)" |
Sets the background color of a component |
| color | "#00FF00", "green", "rgba(0, 255, 0, 0.8)" |
Sets the text color of a component |
| borderColor | "#0000FF", "blue" |
Sets the border color of a component |
Example: Using Color Values
const styles = StyleSheet.create({
text: {
color: '#FF5733',
},
background: {
backgroundColor: 'rgb(255, 87, 51)',
},
border: {
borderColor: 'rgba(0, 0, 255, 0.5)',
borderWidth: 2,
}
});
Note: React Native supports all standard CSS color formats including hex, named colors, RGB, and RGBA.
8. Using Shadows
| Property | Values | Description |
|---|---|---|
| shadowColor | '#000000' |
Color of the shadow |
| shadowOffset | { width: 0, height: 2 } |
Offset of the shadow (x, y) |
| shadowOpacity | 0.2 |
Opacity of the shadow (0 to 1) |
| shadowRadius | 4 |
Radius of the shadow blur |
| elevation | 5 |
Android-specific elevation (0 to 20+) |
Example: Applying Shadows
const styles = StyleSheet.create({
shadowBox: {
width: 100,
height: 100,
backgroundColor: '#fff',
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
}
});
9. Applying Border Styles
| Property | Values | Description |
|---|---|---|
| borderWidth | number |
Width of the border in points |
| borderColor | string |
Color of the border (e.g., 'red', '#00ff00') |
| borderStyle | 'solid', 'dotted', 'dashed' |
Style of the border |
| borderRadius | number |
Radius of the border corners in points |
Example: Basic Border
{'const styles = StyleSheet.create({\n borderedBox: {\n borderWidth: 2,\n borderColor: \'blue\',\n borderRadius: 5,\n padding: 10\n }\n});'}
Example: Dashed Border
{'const styles = StyleSheet.create({\n dashedBox: {\n borderWidth: 1,\n borderColor: \'green\',\n borderStyle: \'dashed\'\n }\n});'}
10. Using Opacity and Visibility
| Property | Values | Description |
|---|---|---|
| opacity | 0 to 1 |
Controls the transparency of a component. 0 is fully transparent, 1 is fully opaque. |
| visibility | visible, hidden |
Controls whether a component is visible or hidden. Unlike opacity, it does not affect layout. |
Example: Setting Opacity
<View style={{ opacity: 0.5 }}>
<Text>This text is semi-transparent</Text>
</View>
Example: Using Visibility
<View style={{ visibility: 'hidden' }}>
<Text>This text is hidden but still takes up space</Text>
</View>
Note:
opacity affects the entire component and all its children, while visibility only affects the component itself.
11. Creating Dynamic Styles
Example: Conditional Style Application
{`const DynamicStyles = () => {
const [isActive, setIsActive] = useState(false);
const dynamicStyle = StyleSheet.create({
container: {
padding: 20,
backgroundColor: isActive ? '#4CAF50' : '#f44336',
},
});
return (
<View style={dynamicStyle.container}>
<Text>Toggle Active State</Text>
</View>
);
};`}
| Property | Values | Description |
|---|---|---|
| StyleSheet.create() | object |
Creates a StyleSheet object with optimized styles |
| style | object | array |
Applies one or more styles to a component |
Note: Styles created with
StyleSheet.create() are cached and optimized for performance.
Warning: Inline styles in
style prop are not optimized and should be avoided for performance-critical components.
Example: Using Style Arrays
{`const StyledComponent = () => {
const baseStyle = StyleSheet.create({
text: {
fontSize: 16,
color: '#333',
},
});
const activeStyle = StyleSheet.create({
text: {
color: '#000',
fontWeight: 'bold',
},
});
return (
<Text style={[baseStyle.text, activeStyle.text]}>
Bold and Dark Text
</Text>
);
};`}
12. Using StyleSheet.flatten Method
The StyleSheet.flatten method is used to resolve a style object that contains nested styles into a single flat style object. This is particularly useful when working with dynamic styles or when combining multiple style objects.
| Parameter | Type | Description |
|---|---|---|
| style | Object | Array |
A style object or an array of style objects to be flattened. |
Example: Flattening Nested Styles
import { StyleSheet } from 'react-native';
const baseStyle = {
fontSize: 16,
color: 'black',
};
const nestedStyle = {
...baseStyle,
fontWeight: 'bold',
};
const flattenedStyle = StyleSheet.flatten(nestedStyle);
console.log(flattenedStyle);
// Output: { fontSize: 16, color: 'black', fontWeight: 'bold' }
Note:
StyleSheet.flatten does not resolve styles that are defined as functions or include conditional logic. It only flattens static style objects.