How to use State with Props in React Native?

May 18, 2022 . Admin

Hi Guys,

This article is focused on react native state and props example. This article goes in detailed on state with props example in react native. you can understand a concept of how to use state with props in react native. we will help you to give example of how to use state and props in functional component in react native. Let's see bellow example how to implement state and props in react native.

There are two types of data that control a component: props and state. props are set by the parent and they are fixed throughout the lifetime of a component. For data that is going to change, we have to use state.

In general, you should initialize state in the constructor, and then call setState when you want to change it.

For example, let's say we want to make text that blinks all the time. The text itself gets set once when the blinking component gets created, so the text itself is a prop. The "whether the text is currently on or off" changes over time, so that should be kept in state.

Step 1: Download Project

In the first step run the following command to create a project.

expo init AppDemo
Step 2: App.js

In this step, You will open the App.js file and put the code.

import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View } from 'react-native';

const Blink = (props) => {
    const [isShowingText, setIsShowingText] = useState(true);

    useEffect(() => {
        const toggle = setInterval(() => {
            setIsShowingText(!isShowingText);
        }, 2000);

        return () => clearInterval(toggle);
    })

    if (!isShowingText) {
        return null;
    }

    return (
        <View style={styles.card}>
            <Text style={styles.text}>{props.text}</Text>
        </View>
    );
}

const App = () => {
    return (
        <View style={styles.container}>
            <Blink text='Mywebtuts.com' />
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    card: {
        backgroundColor:'green',
        padding:20,
        marginBottom:10,
        borderRadius:30,
    },
    text: {
        fontSize:25,
        color:'white',
        fontWeight:'bold',
    },
});

export default App;
Run Project

In the last step run your project using the below command.

expo start

You can QR code scan in Expo Go Application on mobile.

Output :

It will help you...

#React Native