React Native does not use traditional CSS like web development. Instead, it uses a JavaScript-based StyleSheet API similar to inline styles.
You can apply styles directly to components using JavaScript objects.
import React from 'react';
import { Text, View } from 'react-native';
const App = () => {
return (
<View>
<Text style={{ color: 'blue', fontSize: 20 }}>Hello, React Native!</Text>
</View>
);
};
export default App;
* Pros: Quick and easy for small styles.
* Cons: Hard to maintain for larger projects.
StyleSheet
API (Recommended)The StyleSheet.create
method helps optimize styles by preventing unnecessary re-renders.
import React from 'react';
import { Text, View, StyleSheet } from 'react-native';
const App = () => {
return (
<View style={styles.container}>
<Text style={styles.text}>Styled with StyleSheet!</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f0f0f0',
},
text: {
fontSize: 20,
color: 'blue',
fontWeight: 'bold',
},
});
export default App;
* Pros: Improves performance, easier to maintain.
* Cons: Still lacks CSS features like media queries.
Styled-components allow writing styles similarly to CSS but in JavaScript.
npm install styled-components
or
yarn add styled-components
import React from 'react';
import { Text, View } from 'react-native';
import styled from 'styled-components/native';
const Container = styled(View)`
flex: 1;
justify-content: center;
align-items: center;
background-color: #f0f0f0;
`;
const StyledText = styled(Text)`
font-size: 20px;
color: blue;
font-weight: bold;
`;
const App = () => {
return (
<Container>
<StyledText>Styled with Styled Components!</StyledText>
</Container>
);
};
export default App;
* Pros: Looks like CSS, easy to manage styles.
* Cons: Can affect performance slightly.
Platform
API)Use Platform
API to style differently based on iOS or Android.
import { Platform, StyleSheet } from 'react-native';
const styles = StyleSheet.create({
text: {
fontSize: 20,
color: Platform.OS === 'ios' ? 'blue' : 'green',
},
});
* Pros: Customize styles for each platform.
* Cons: Adds complexity.
For global styles, you can use:
react-native-paper
or tailwind-rn
Example using styled-components
theme:
import { ThemeProvider } from 'styled-components/native';
const theme = {
colors: {
primary: 'blue',
background: '#f0f0f0',
},
};
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>;
Method | Best For |
---|---|
Inline Styles | Quick styling, small components |
StyleSheet API | Most recommended, optimized |
Styled Components | Better readability, theme-based apps |
Platform API | Platform-specific styles |
Global Themes | Large apps with consistent design |