DEV Community

Cover image for Mastering React Native with TypeScript: From Basics to Brilliance - Part 1
Rushikesh Pandit
Rushikesh Pandit

Posted on

Mastering React Native with TypeScript: From Basics to Brilliance - Part 1

Are you ready to dive into the world of mobile app development without mastering two separate languages for iOS and Android? Meet React Native—the game-changing framework from Facebook that lets you build high-performance, cross-platform apps using the language you already love: JavaScript (and in our case, TypeScript)!

With React Native, you can build apps that look, feel, and perform as a true native app would. No wonder it's powering industry-leading apps like Instagram, Airbnb, and Tesla.

Kickstarting your journey into the world of React Native 0.76 with TypeScript, we are going to go over what the core building blocks of any application are. Whether you're a curious beginner or an experienced developer seeking to hone your abilities in TypeScript, this guide will get you moving toward mobile development greatness.

We're covering everything you need to know to build your first app:

  • The Core Components include View, Text, and ScrollView
  • Styling techniques that make your UI pop
  • Managing Props and State for dynamic interactions
  • Mastering lists with FlatList for seamless data handling

By the end of this series, you’ll not only understand the foundation of React Native but also have practical, real-world code snippets to kickstart your app development journey. Let’s make your dream app a reality—starting now!!

Core Components in React Native

Core components are the basic building blocks of every React Native application. They connect the JavaScript world with the native world, and that is where you get the building blocks to craft amazing user interfaces. Let's take a look at each of them.

1 . View

The View component is the fundamental container in React Native. It’s used to group and layout other components. Think of it as a div in web development.

Example: Creating a Centered Box

import React from 'react';
import { View, StyleSheet } from 'react-native';

const App = () => (
  <View style={styles.container}>
    <View style={styles.box} />
  </View>
);

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  box: { width: 100, height: 100, backgroundColor: 'blue' },
});

export default App;
Enter fullscreen mode Exit fullscreen mode

Here, we use flex: 1 to ensure the View fills the entire screen, and justifyContent and alignItems center the box.

2 . Text

The Text component is used for rendering text on the screen. It supports various text styles and nested elements.

Example: Displaying Styled Text

import React from 'react';
import { Text, StyleSheet } from 'react-native';

const App = () => (
  <Text style={styles.text}>Hello, React Native with TypeScript!</Text>
);

const styles = StyleSheet.create({
  text: { fontSize: 20, color: 'purple', textAlign: 'center', marginTop: 20 },
});

export default App;
Enter fullscreen mode Exit fullscreen mode

Notice how we use fontSize, color, and textAlign to style the Text component.

3 . Image

The Image component is used to display images. It supports both local and remote image sources.

Example: Displaying a Remote Image

import React from 'react';
import { Image, StyleSheet } from 'react-native';

const App = () => (
  <Image
    source={{ uri: 'https://reactnative.dev/img/tiny_logo.png' }}
    style={styles.image}
  />
);

const styles = StyleSheet.create({
  image: { width: 100, height: 100, borderRadius: 10 },
});

export default App;
Enter fullscreen mode Exit fullscreen mode

The borderRadius property gives the image rounded corners.

4 . TextInput

The TextInput component captures user input. It supports properties like placeholder, onChangeText, and value.

Example: Handling User Input

import React, { useState } from 'react';
import { TextInput, StyleSheet, View, Text } from 'react-native';

const App = () => {
  const [input, setInput] = useState<string>('');

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="Type here..."
        value={input}
        onChangeText={setInput}
      />
      <Text>You typed: {input}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: { padding: 20 },
  input: { borderWidth: 1, borderColor: '#ccc', padding: 10, borderRadius: 5, marginBottom: 10 },
});

export default App;
Enter fullscreen mode Exit fullscreen mode

The onChangeText handler updates the state with the user’s input.

5 . TouchableOpacity

The TouchableOpacity component enables touch interactions with a fading effect.

Example: Creating a Button

import React from 'react';
import { TouchableOpacity, Text, StyleSheet } from 'react-native';

const App = () => (
  <TouchableOpacity style={styles.button} onPress={() => alert('Button Pressed!')}>
    <Text style={styles.text}>Press Me</Text>
  </TouchableOpacity>
);

const styles = StyleSheet.create({
  button: { backgroundColor: 'blue', padding: 10, borderRadius: 5 },
  text: { color: 'white', textAlign: 'center' },
});

export default App;
Enter fullscreen mode Exit fullscreen mode

The onPress handler triggers an action when the button is tapped.

6 . ScrollView

The ScrollView component allows for scrollable content. It’s ideal for layouts with a small amount of content that won’t require heavy performance optimization.

Example: Rendering a Scrollable List

import React from 'react';
import { ScrollView, Text, StyleSheet } from 'react-native';

const App = () => (
  <ScrollView contentContainerStyle={styles.container}>
    {Array.from({ length: 20 }, (_, i) => (
      <Text key={i} style={styles.text}>Item {i + 1}</Text>
    ))}
  </ScrollView>
);

const styles = StyleSheet.create({
  container: { padding: 10 },
  text: { fontSize: 16, marginVertical: 5 },
});

export default App;
Enter fullscreen mode Exit fullscreen mode

Here, we dynamically generate 20 items and render them inside a ScrollView.

7 . FlatList

The FlatList component is designed for rendering large datasets efficiently. It only renders items currently visible on the screen, significantly improving performance.

Example: Rendering a List

import React from 'react';
import { FlatList, Text, View, StyleSheet } from 'react-native';

const data = [
  { id: '1', name: 'Item 1' },
  { id: '2', name: 'Item 2' },
  { id: '3', name: 'Item 3' },
];

const App = () => (
  <FlatList
    data={data}
    keyExtractor={(item) => item.id}
    renderItem={({ item }) => (
      <View style={styles.item}>
        <Text style={styles.text}>{item.name}</Text>
      </View>
    )}
  />
);

const styles = StyleSheet.create({
  item: {
    padding: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#ccc',
  },
  text: {
    fontSize: 18,
  },
});

export default App;
Enter fullscreen mode Exit fullscreen mode

Key Difference Between FlatList and ScrollView:

  • Use FlatList for large, dynamic datasets to optimize performance.

  • Use ScrollView for smaller datasets or static content.

Styling in React Native

Styling in React Native is achieved using the StyleSheet API. It borrows heavily from CSS but is tailored to work with native platforms for optimal performance.

1 . StyleSheet API

The StyleSheet API provides a way to define styles separately and reuse them across components.

Example: Creating Reusable Styles

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

const App = () => (
  <View style={styles.container}>
    <Text style={styles.text}>Reusable Styles with StyleSheet</Text>
  </View>
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f0f0f0',
  },
  text: {
    fontSize: 20,
    color: 'blue',
  },
});

export default App;
Enter fullscreen mode Exit fullscreen mode

2 . Flexbox Layout

React Native employs Flexbox for layout management. Flexbox helps to define the alignment, distribution, and spacing of elements within a container.

Example: Aligning Items Horizontally

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 10,
  },
});
Enter fullscreen mode Exit fullscreen mode

3 . Platform-Specific Styling

React Native allows platform-specific styles using the Platform module.

Example: Conditional Styling

import { Platform, StyleSheet } from 'react-native';

const styles = StyleSheet.create({
  text: {
    fontSize: Platform.OS === 'ios' ? 20 : 18,
    color: Platform.OS === 'ios' ? 'blue' : 'green',
  },
});
Enter fullscreen mode Exit fullscreen mode

Props and State Management

1 . Props

Props allow you to pass data from a parent component to a child component.

Example: Custom Greeting Component

import React from 'react';
import { Text } from 'react-native';

const Greeting = ({ name }: { name: string }) => (
  <Text>Hello, {name}!</Text>
);

const App = () => <Greeting name="React Native" />;

export default App;
Enter fullscreen mode Exit fullscreen mode

2 . State Management with useState

The useState hook is used to manage state in functional components.

Example: Counter Component

import React, { useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

const Counter = () => {
  const [count, setCount] = useState<number>(0);

  return (
    <View style={styles.container}>
      <Text style={styles.text}>Count: {count}</Text>
      <Button title="Increase" onPress={() => setCount(count + 1)} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  text: {
    fontSize: 18,
    marginBottom: 10,
  },
});

export default Counter;
Enter fullscreen mode Exit fullscreen mode

3 . Typing Props with TypeScript

Using TypeScript ensures type safety when passing props.

Example: Typing Props

interface GreetingProps {
  name: string;
}

const Greeting = ({ name }: GreetingProps) => (
  <Text>Hello, {name}!</Text>
);
Enter fullscreen mode Exit fullscreen mode

That's it for today. In the next part of this series, we’ll explore advanced topics like navigation, animations, hooks, and working with APIs.

Feel free to reach out to me if you have any questions or need assistance.
LinkedIn: https://www.linkedin.com/in/rushikesh-pandit-646834100/
GitHub: https://github.com/rushikeshpandit
Portfolio: https://www.rushikeshpandit.in

#ReactNative #TypeScript #MobileDevelopment #SoftwareEngineering #DevCommunity

Top comments (0)