Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To check or handle NaN in react native, use the isNaN() method it will return if the value is not a number, if the value is a number it will return false.

Let’s understand when the isNaN method returns false or when true.

Number.isNaN(NaN);        // true
Number.isNaN(Number.NaN); // true
Number.isNaN(0 / 0);      // true

// e.g. these would have been true with global isNaN()
Number.isNaN('NaN');      // false
Number.isNaN(undefined);  // false
Number.isNaN({});         // false
Number.isNaN('blabla');   // false

// These all return false
Number.isNaN(true);
Number.isNaN(null);
Number.isNaN(37);
Number.isNaN('37');
Number.isNaN('37.37');
Number.isNaN('');
Number.isNaN(' ');

Today, I’m going to show you How do I check or handle NaN in react native, as above mentioned, I’m going to use the isNaN() method it will return false when the value is a number.

Let’s start today’s tutorial how do you check or handle NaN in react native?

React native check NaN example

Here, we will take the example of two states one state has some data and another has a NaN value, we will check both states consoles the NaN state name.

import React, { useState, useEffect } from "react";
import { View, Text } from "react-native";
export default function App() {
  const [str1] = useState("Infinitbility");
  const [str2] = useState(34);

  useEffect(() => {
    if (isNaN(str1)) {
      console.log("str1 is not a number");
    } else {
      console.log("str1 is number");
    }

    if (isNaN(str2)) {
      console.log("str2 is not a number");
    } else {
      console.log("str2 is number");
    }
  }, []);

  return (
    <View>
      <Text>{isNaN(str1) ? "str1 not a number" : "str1 is number"}</Text>
      <Text>{isNaN(str2) ? "str2 not a number" : "str2 is number"}</Text>
    </View>
  );
}

In the above example, I have also put the example check NaN in render code here to check NaN we can use the ternary operator.

I hope it helps you, All the best đź‘Ť.

React Native, check or handle nan example
React Native, check or handle nan example

Try it yourself