How to Generate OTP in React Native

Importance of One Time Passwords are increasing in modern mobile apps. Developers add an extra layer of security in their apps by generating and verifying OTPs. When it comes to verify mobile numbers, OTPs are the way to go.

In this blog post, I am creating a react native OTP generator. This will be helpful when you need to generate OTPs in the front end. It’s all about a function which returns random digits of predefined length.

Following is the JavaScript function to generate OTP in react native.

const generateOTP = (length) => {
    const digits = '0123456789';
    let OTP = '';
    for (let i = 0; i < length; i++) {
      OTP += digits[Math.floor(Math.random() * 10)];
    }
    return OTP;
  };

The OTP generated by the above function will only have digits. If you want an alpha numeric OTP then you can use the following function.

const generateOTP = (length) => {
    const characters =
      '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    const characterCount = characters.length;
    let OTP = '';
    for (let i = 0; i < length; i++) {
      OTP += characters[Math.floor(Math.random() * characterCount)];
    }
    return OTP;
  };

In the following react native example, I generate alpha numeric OTP when the Button is pressed. The six character OTP is shown as Text.

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

const App = () => {
  const [OTP, setOTP] = useState('');
  const generateOTP = (length) => {
    const characters =
      '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    const characterCount = characters.length;
    let OTPvalue = '';
    for (let i = 0; i < length; i++) {
      OTPvalue += characters[Math.floor(Math.random() * characterCount)];
    }
    setOTP(OTPvalue);
    return OTPvalue;
  };

  return (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
      <Button
        onPress={() => generateOTP(6)}
        title="Generate OTP"
        color="#841584"
      />
      <Text>{OTP}</Text>
    </View>
  );
};

export default App;

Following is the output of the OTP generator example.

react native OTP generator

I hope this react native tutorial will be helpful for you.

Leave a Reply

%d bloggers like this: