DEV Community

Cover image for Fundamental React Native Components You Need To Know About
Nitin Sharma
Nitin Sharma

Posted on

Fundamental React Native Components You Need To Know About

React Native enables you to create native applications from a single codebase. The applications created with React Native are native apps rather than web applications.

Over the last few years, React Native has consistently ranked at the top in terms of popularity. As per Statista, around 40% of developers globally use React Native.

Stats

It has become one of the most popular frameworks due to its single codebase, usage of Javascript, and focused on performance.

It has a lot going for it. The biggest one is the hybrid nature of the framework. Hybrid apps are all the rage these days with top apps like Twitter & Instagram bringing the advantages that come with them into the limelight.

A single codebase may now be utilized to build an app for both Android & iOS, instead of the previous requirement of maintaining two separate codebases written in Java and Swift respectively. This means a faster time to market & updates.

Apart from that, it is also free & open source and has a large developer community with thousands of members globally.

React Native features hot reloading, which means only the code that is changed is patched, which saves a huge amount of time. Moreover, the codebase follows a similar pattern and concepts to a React project so web developers can feel at home using this framework to build mobile apps.

Time-tested practices such as D.R.Y(Don’t Repeat Yourself) can be easily implemented. Based on estimates, around 90% of the code between Android and iOS may be reused.

To make the development seamless, React Native offers a broad array of components, that are essentially just wrappers around native ones, enabling you to easily plug in your native code as well.

Deep Dive into React Native Components

React Native has various built-in components that assist you in breaking down UI into reusable sections. These elements are specified within functions or classes. Simply import these components from React Native, and use them freely across the file.

The primary application of the React Native components is to enable developers to quickly design user interfaces using a predefined set of components.

Under the hood, these components are simply produced using JavaScript, however, iOS & Android do not support JS hence it uses platform-specific APIs and modules to convert into native components at runtime.

Since the framework offers a plethora of components, a handful stands out as the most essential ones.

Basic Components

1. View

Consider it a container, a div, or a section. The view component displays slideshows, text, images, user input, and nearly anything else you can think of.

It gets transformed into Android and iOS components during runtime.

import React from "react";
import { View, Text } from "react-native";
const App = () => {
  return (
    <View style={{ margin: 10 }}>
      <Text style={{ marginBottom: 10 }}>
        Hello Readers, I'm inside View Component
      </Text>
      <Text style={{ marginBottom: 10 }}>You can also define image</Text>
    </View>
  );
};
export default App;
Enter fullscreen mode Exit fullscreen mode

Here we have the View component, inside which we have defined a component called Text.

2. Text

It is a component for displaying text inside an app. It supports nesting, and touch events along with standard styling options such as custom fonts, font size, etc.

It is important to note that you cannot put text directly inside the View component. In other words, the text has to be always wrapped in the Text component.

import React from "react";
import { View, Text } from "react-native";
const App = () => {
  return (
    <View style={{ margin: 10 }}>
      <Text style={{ marginBottom: 10 }}>Hello, I am Text Component</Text>
      <Text style={{ marginBottom: 10 }}>I am also a Text Component</Text>
    </View>
  );
};
export default App;
Enter fullscreen mode Exit fullscreen mode

3. Image

The next React Native component is Image. It lets you add images to your app.

Additionally, you may include network images, temporary images, static images, and more.

import React from "react";
import { View, Text, Image } from "react-native";
const App = () => {
  return (
    <View>
      <Text>The Image Component is next to me.</Text>
      <Image
        source={{
          uri: "https://reactnative.dev/docs/assets/p_cat2.png",
        }}
        style={{ width: 200, height: 200 }}
      />
      <Image
        style={styles.logo}
        source={{
          uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg==',
        }}
      />
</View>
  );
};
export default App;
Enter fullscreen mode Exit fullscreen mode

There are also methods for accessing image size or prefetching the image.

For instance, we may obtain an image’s size using:

Image.getSize(uri, success, [failure]);
Enter fullscreen mode Exit fullscreen mode

4. TextInput

This component enables the user to add input.

You can add more functionality to it by passing props to save the input response from the user, updating some sections, and text, or viewing the app after the user submits the input.

Other events, such as onChange, onSubmitEditing, onScroll, etc., can be used to modify the TextInput component.

import React from "react";
import { View, Text, TextInput } from "react-native";
const App = () => {
  return (
    <View style={{ margin: 10 }}>
      <Text>The user can type something.</Text>
      <TextInput
        style={{
          height: 30,
          borderColor: "black",
          borderWidth: 1,
        }}
        defaultValue="I am a Text Input"
      />
    </View>
  );
};
export default App;
Enter fullscreen mode Exit fullscreen mode

5. ScrollView

You may scroll specific areas horizontally or vertically using ScrollView components. In other words, you may utilize ScrollView if you have a lot of children components that may not fit into the screen at once hence you may want to show some of them after scrolling.

To use it, you simply need to wrap the section within the ScrollView component.

Here, ScrollView renders all of its child components at the same time which might result in poor rendering and performance.

import React from "react";
import { View, Text, Image, ScrollView, TextInput } from "react-native";
const App = () => {
  return (
    <ScrollView>
      <Text style={{ fontSize: 100 }}>
        I am a text component inside ScrollView component
      </Text>
      <Text style={{ fontSize: 100 }}>Some more text</Text>
    </ScrollView>
  );
};
export default App;
Enter fullscreen mode Exit fullscreen mode

User Interface

1. Button

The next component is called “Button” which as the name suggests, helps you create buttons that your users can interact with. These are just touch-sensitive elements that are used to control the screen and carry out operations.

You can even customize or build some new buttons with the help of TouchableOpacity or TouchableWithoutFeedback. There’s also TouchableHighlight which works by cloning its child and applying responder props to it.

import React from "react";
import { Button, View, Alert } from "react-native";
const App = () => (
  <View>
    <Button title="Click Me" onPress={() => Alert.alert("I am pressed")} />
  </View>
);
export default App;
Enter fullscreen mode Exit fullscreen mode

2. Switch

The switch component is basically an on/off button or a boolean value. The user can change based on their preference.

It is a controlled component that needs to be manually updated by you using the “onValueChange()” callback function.

As seen in the example, we imported the Switch component and passed two props: one to change the state and the other to show the state.

import React, { useState } from "react";
import { View, Switch, StyleSheet } from "react-native";
const App = () => {
  const [isTrue, setIsTrue] = useState(true);
  const toggleSwitch = () => setIsTrue((previousState) => !previousState);
  return (
    <View style={styles.container}>
      <Switch onValueChange={toggleSwitch} value={isTrue} />
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
});
export default App;
Enter fullscreen mode Exit fullscreen mode

List Views

1. FlatList

This component displays the data in the list format. In the FlatList component, you need to know two crucial props i.e. “data” and “renderItem”.

In the data prop, we need to pass the data we want to render. And the renderItem prop will render the data one by one.

Here you may see a warning if you haven’t passed a key as a prop.

import React from "react";
import {
  SafeAreaView,
  View,
  FlatList,
  StyleSheet,
  Text,
  StatusBar,
} from "react-native";
const DATA = [
  {
    id: "1",
    title: "Hello",
  },
  {
    id: "2",
    title: "Bye",
  },
  {
    id: "3",
    title: "See You",
  },
];
const Item = ({ title }) => (
  <View style={styles.item}>
    <Text style={styles.title}>{title}</Text>
  </View>
);
const App = () => {
  const renderItem = ({ item }) => <Item title={item.title} />;
  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={DATA}
        renderItem={renderItem}
        keyExtractor={(item) => item.id}
      />
    </SafeAreaView>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: StatusBar.currentHeight || 0,
  },
  item: {
    backgroundColor: "blue",
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 18,
  },
});
export default App;
Enter fullscreen mode Exit fullscreen mode

2. SectionList

The React Native SectionList component is a list view component that divides the data list into broken logical sections.

It has support for a wide variety of modern features such as scroll loading, list footer as well as pull to refresh functionalities.

import React from "react";
import {
  StyleSheet,
  Text,
  View,
  SafeAreaView,
  SectionList,
  StatusBar,
} from "react-native";
const DATA = [
  {
    title: "Starter",
    data: ["Bacon Rings", "Tuna Empanadillas", "Paneer Crispy"],
  },
  {
    title: "Main Course",
    data: [
      "Shrimp Quinoa Fried Rice",
      "Salmon Mac And Cheese",
      "Creamy Garlic Paprika Shrimp",
    ],
  },
];
const Item = ({ title }) => (
  <View style={styles.item}>
    <Text style={styles.title}>{title}</Text>
  </View>
);
const App = () => (
  <SafeAreaView style={styles.container}>
    <SectionList
      sections={DATA}
      keyExtractor={(item, index) => item + index}
      renderItem={({ item }) => <Item title={item} />}
      renderSectionHeader={({ section: { title } }) => (
        <Text style={styles.header}>{title}</Text>
      )}
    />
  </SafeAreaView>
);
const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: StatusBar.currentHeight,
    marginHorizontal: 16,
  },
  item: {
    backgroundColor: "#f9c2ff",
    padding: 20,
    marginVertical: 8,
  },
  header: {
    fontSize: 32,
    backgroundColor: "#fff",
  },
  title: {
    fontSize: 18,
  },
});
export default App;
Enter fullscreen mode Exit fullscreen mode

Creating Custom React Native Components

React Native performs admirably when an iOS or Android app is developed from a single codebase, with the same components used for both platforms. The inbuilt components are great for most interfaces & features, but they may fall short in some places.

Since iOS and Android operate differently, you may want to design some unique, custom components that are based on the specific operating system.

Below is an example of a custom component.

import React from 'react';
import { View, Text } from 'react-native';
const CustomTextComponent = () => {
  return (
    <View> 
      <Text>Hello, I am a Custom Component</Text>
    </View> 
  );
}
export default CustomTextComponent;
Enter fullscreen mode Exit fullscreen mode

That’s it, you have created a custom component. Now you can import it into a file and re-use it.

Using the Locofy.ai plugin, you can take your designs in Figma and Adobe XD to production-ready frontend code in a matter of a few hours by letting the plugin generate the React Native components, following the best practices and industry standards.

You can simply tag the elements in your design and then export the code, in either JavaScript or TypeScript using the Locofy Builder, which is a natural transition between design and high-quality code.

The Locofy Builder will allow you to customize your project and generate React Native components. You can even specify the props you want the components to accept, making the code highly extendible. What’s more is that you can export just the components instead of the entire code base, allowing you to quickly plug them into your existing projects.

Go from designs to native apps using the Locofy.ai plugin and ship products 5x faster!

Hope you like it.

That’s it — thanks.

Originally published at https://blog.locofy.ai.

Top comments (0)