How calculate automatically without press a button? (In a text input)

Hi, I’m recently learning react native and I have this project:

This code are in App.js, the input “Perimetro” is the perimeter, in the text “resultado” should appear the result of the operation.

I need calculate automatically the area of ​​a circumference without a button, but I don’t know how to achieve it, maybe I have searched wrong, but I have not found any React Native project where something is calculated without a button, any suggestions? Examples?

Thanks

Maybe onChangeText is what you want.
Sample code:

import * as React from 'react';
import { TextInput } from 'react-native-paper';
import { View, Text } from 'react-native';

const MyComponent = () => {
  const [text, setText] = React.useState('');

  return (
    <View>
      <TextInput
      label="Perimeter"
      value={text}
      onChangeText={text => setText(text)}
      />
      <Text>Result:{text}</Text>
    </View>
  );
};

export default MyComponent;
1 Like

Hi, thanks for answering me.
Now I made this code based in your example with onChangeText, but it isn’t working for me.


export default function App() {

  const [text, setText] = React.useState('');

      const pi = 3.1415;

      const total = (pi * Math.pow((text/(2*pi))),2).toFixed(2); //toFixed for two decimals

      setText({total});

      return (

        <View style={styles.container}>

          <View>

            <Image 

                source={area}

                style={{height: 150, width: 150, alignSelf: 'flex-start'}}

            />

          </View>

          <View style={styles.viewForm}>

            <TextInput placeholder="  Perímetro" 

              keyboardType="numeric" 

              style={styles.input} 

              value={text}

              onChangeText={text => setText(text)}

            >

            </TextInput>

            <Text style={styles.resultado}>resultado:{text}</Text>

          </View>

          <StatusBar style="auto" />

        </View>

      );

}

You should assign a function for onChangeText
Try this:

export default function App() {
  const [text, setText] = React.useState('');
  const pi = 3.1415;
  const total = (value) => {
    const result = (pi * Math.pow(value / (2 * pi), 2)).toFixed(2);
    setText(result);
  }; //toFixed for two decimals

  return (
    <View>
      <View>
        <TextInput
          placeholder="  Perímetro"
          keyboardType="numeric"
          onChangeText={total}
        />
        <Text>resultado:{text}</Text>
      </View>
    </View>
  );
}
1 Like

That worked perfectly fine and I also understood it. Thanks :smiley: !!!

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.