Logo
Core Concepts

Styling

How to style your React Native components to create visually appealing and responsive applications.

Introduction to Styling in React Native

Styling in React Native is quite different from styling in HTML and CSS. React Native uses a JavaScript-based approach to styling, leveraging the StyleSheet API to create styles that are applied to components.

Inline Styling

Overview

Inline styling allows you to apply styles directly within your JSX code. However, it's generally not recommended for larger projects due to maintainability issues.

Example

Here's an example of inline styling:

import React from 'react';
import { View, Text } from 'react-native';
 
const InlineExample = () => {
  return (
    <View style={{ padding: 20 }}>
      <Text style={{ fontSize: 18, color: 'blue' }}>Inline Styling Example</Text>
    </View>
  );
};
 
export default InlineExample;

StyleSheet API

Overview

The StyleSheet API allows you to create styles in a more organized and optimized manner. It's the recommended way to style your React Native components.

Example

Here's an example using StyleSheet:

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
 
const StylesheetExample = () => {
  return (
    <View style={styles.container}>
      <Text style={styles.text}>StyleSheet Example</Text>
    </View>
  );
};
 
const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  text: {
    fontSize: 18,
    color: 'green',
  },
});
 
export default StylesheetExample;

Theming

Overview

Theming allows you to maintain a consistent look and feel across your application. You can use context or third-party libraries like styled-components for more advanced theming.

Example

Here's a simple example using context for theming:

import React, { createContext, useContext } from 'react';
import { View, Text } from 'react-native';
 
const ThemeContext = createContext('light');
 
const ThemedText = () => {
  const theme = useContext(ThemeContext);
  const textColor = theme === 'light' ? 'black' : 'white';
 
  return <Text style={{ color: textColor }}>Themed Text</Text>;
};
 
const ThemingExample = () => {
  return (
    <ThemeContext.Provider value="dark">
      <View>
        <ThemedText />
      </View>
    </ThemeContext.Provider>
  );
};
 
export default ThemingExample;

Understanding how to effectively style your components is crucial for building visually appealing React Native applications. Feel free to explore each method to find what best suits your project's needs.

Book a conversation with us for personalize training today!

Was this helpful?
Logo