Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To add two numbers in react native, use the + addition operator it will add if your value datatype is a number else if your value datatype is string first convert it using parseInt() and then perform addition operation.

In the following example, we will take the sample numbers, and strings and perform add operation using the + addition operator.

Adding Two numbers example

let num1 = 30;
let num2 = 34;

num1 + num2; // 64

Adding Two string numbers example

let num1 = "30";
let num2 = "34";

parseInt(num1) + parseInt(num2); // 64

Today, I’m going to show you How do i add two numbers in react native, as mentioned above here, I’m going to use the + addition operator.

Let’s start today’s tutorial how do you add two numbers in react native?

In this example, we will do

  1. take an example of a number and string number state
  2. adding two numbers example
  3. adding two string numbers example
  4. print the output on the page screen
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet } from 'react-native';

const App = () =>  {
    const [firstNum, setFirstNum] = useState(24);
    const [secondNum, setSecondNum] = useState(24);

    const [firstStr, setFirstStr] = useState("24");
    const [secondStr, setSecondStr] = useState("24");

    return (
        <View style={styles.container}>
            <Text style={styles.paragraph} >{`adding two numbers example`}</Text>
            <Text style={styles.paragraph} >{firstNum + secondNum}</Text>
            <Text style={styles.paragraph} >{`adding two string numbers example`}</Text>
            <Text style={styles.paragraph} >{parseInt(firstStr) + parseInt(secondStr)}</Text>
        </View>
    );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

export default App;

In the above react native example, we have taken the sample numbers and string numbers state, and perform adding two numbers example, and adding two string numbers example.

React Native, add two numbers example
React Native, add two numbers example

Try it yourself

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