Home React Native How to Create Random String in React Native?

How to Create Random String in React Native?

by Shahriar Sagor

Hello Dev’s today now in this post i will show you How to Create Random String in React Native? Here in this tutorial i will teach you react native random string example. if you have any question about the random string generator by using the react native then here I will give simple example with the solution. here in this example i will help you how to create random string in react native. This example is step by step explain about how to implement random string in react native. here we will do the following things for how to generator random string in react native.

Let’s start and following example:

Step 1: Download Project

This is the first step need to run the following command to create a new project.

expo init ExampleApp
Step 2: App.js

Now in this step, we need to open the App.js file and then 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

Read Also: How to use SetTimeout in React Native?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like