Technology3 min read

How to create a component in React Native?

Abhishek Ahlawat

By Abhishek Ahlawat — Recently

Founder of StudyTonight and a MERN fullstack developer. Writes about JavaScript, web development, Linux, and tech.

Summarize this article using AI

In react native, we can create a component using function or class. Before introducing the React Hook API in react native, the class component is the only way to use the props and state in our app but now we can also add state and other functionality to the function component. And right now the default component used in react native is the function component.

What is a component in React Native?

In react-native, the component is a place where we add our running code that executes in real-time. just like we add all our code into the body tag on a web page. in react native we add all the running code and other components in our base (class/function) component.

let's understand both class and function-based components with examples.

React Native - Class Component

Here is a simple example of a class-based component that just prints the Hello, React Native onto the screen.

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

class New extends Component {
  render() {
    return (
      <Text>Hello, React Native</Text>
    );
  }
}

export default New;

react native class based component


Explanation:

Here, we first import React and Component from the react library. That is used to create a component. Second, we import a Text component that’s a core component of react-native.

Then we create a class name New and extend all the components under it. And then we render a Text component as a react element that’s returned by the return method. Remember in react a class must have a render method and return method to execute.

And then we export the New class as a default element. So whenever any other component calls this file then it will automatically return the class component as a default component.

React Native - Function component

Here is a simple example of a function-based component that just returns the Hello, React Native Text.

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

const New = () => {
  return (
    <Text>Hello, React Native</Text>
  );
}

export default New;

react native function based component

Explanation:

Here we declare a function New that returns a text element. Remember whatever a function component return is rendered as a react element. So, we don't need to use the render() method inside it.


Spotted something outdated or wrong?

Liked this? See more StudyTonight posts in Google results.

Add StudyTonight as a preferred source
Next questLIVE OPSStep 2 / 3

Practice real incidents in the browser

System Design Ops — put out fires, ship fixes, and stack XP. Reading done. Time to play.

Play System Design
  • +XP

    Every sim

  • Incidents

    Live ops

  • Ranks

    Climb up

Read next