New Tutorials:   NUMPY    TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL    Matplotlib    C++ Programs
CLOSE
   ReactNative  React Components  Mobile Applications  
   Technology    Programming

How to create a component in React Native?

         
  FEBRUARY 10, 2021   by yashpal

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.


RELATED POSTS



Subscribe and receive amazing posts directly in your inbox.