Joseph Jude

Consult . Code . Coach

Creating a Custom Component in React Native


code . nodejs . rn . react

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


Like the post? Retweet it. Got comments? Reply.

Creating a Custom Component in React Native by @jjude: https://t.co/hWGQ1dj1VS

— Joseph Jude (@jjude) November 25, 2017
Share this on: Twitter / /

Comments

comments powered by Disqus