React Native Random String Example

Jun 17, 2022 . Admin

Hi Guys,

In this example, you will learn how to generator random string in react native. I’m going to show you about random string generator using react native. In this article, we will implement a how to implement random string in react native. We will look at example of react native random string example. Here, Creating a basic example of how to create random string in react native.

Let's start following example:

Step 1: Download Project

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

expo init ExampleApp
Step 2: App.js

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

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

const App = () => {
    const [string, setString] = React.useState('String');

    const generateRandomString = (lenth) => {
        const char = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
        const random = Array.from(
            {length: lenth},
            () => char[Math.floor(Math.random() * char.length)]
        );
        const randomString = random.join("");
        return setString(randomString);
    }

    return (
        <View style={styles.container}>
            <Text>{string}</Text>
            <View style={styles.buttonContainer}>
                <Button 
                    title='generate random string'
                    onPress={() => generateRandomString(10)}
                />
            </View>
        </View>
    );
}

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

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