The StyleSheet API in React Native is used to create optimized, reusable, and structured styles for mobile components. It works similarly to CSS, but uses JavaScript objects instead of traditional stylesheets.
Styles in React Native are defined using the StyleSheet.create() method. Each key represents a style object that can be applied to a component.
// Import StyleSheet from react-native
import { StyleSheet } from 'react-native';
// Create a stylesheet object
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
text: {
fontSize: 20,
color: 'blue'
}
});
export default styles;
// Applying styles to React Native components
import React from 'react';
import { View, Text } from 'react-native';
import styles from './styles';
const App = () => {
return (
<View style={styles.container}>
<Text style={styles.text}>Hello StyleSheet</Text>
</View>
);
};
export default App;
The container centers its content using flexbox, and the text appears in blue with a font size of 20. Styles are reused efficiently without inline duplication.
Adjust the controls below to see how React Native style properties affect a component and how the StyleSheet code looks.
StyleSheet.create() instead of inline styles