Joseph Jude

Creating a Custom Component in React Native

2017.11.25 / code / nodejs / rn / react /

It is easy to compose our own custom components in React Native. In this post, we compose a simple quote component.

React Native comes with lot of built-in components. In the last post on Adding buttons with images in React Native, we used view, touchableopacity, and text components.

We can create our applications with these base components. But it is easier to compose our own components according to the application needs. In this post, we are going to compose one such component to display quotes.

Custom Component in React Native

We need to understand props before we get to create our own components. props is a way to pass values to components, similar to passing parameters to functions.

In this post, we are going to compose a very simple quote component. It will take two parameters - a quote and the author of that quote. Then it will display both of them under a base view component.

Code to create this custom Quote component is as below. Store it in a separate file called Quote.js.

import React, { Component } from 'react';

import {
  View,
  Text,

} from 'react-native';

export class Quote extends Component {
  render() {
    return (
      <View>
        <Text>{this.props.QuoteText}</Text>
        <Text>-{this.props.QuoteAuthor}</Text>
      </View>

    );
  }
}

export default Quote;

Now we can use this custom component. We have to import it and pass the props, which are in this case QuoteText and QuoteAuthor.

import React, { Component } from 'react';

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

import Quote from "./Quotes";

export default class Quotes extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Quote 
        QuoteText="If God is your partner, make your plans BIG!" 
        QuoteAuthor="D.L. Moody" 
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

You can use this custom component, as many times as you want. Isn't the code much cleaner with this custom component?

Like what you read in this post? Feel free to read all other posts in this series.

You can also subscribe with the below form to get these posts as soon as I post them.

This is part of Learn React Native series


Share this post on

Twitter | | |
Sign up for my weekly newsletter

I will send blog updates to this email. You can unsubscribe at any time using the link in those emails.