Sachu
Sachu

Reputation: 187

How to pass a variable in a component to a function

I'm using a library to create a calculator and want to pass the value I compute to another function.

Library Here: https://www.npmjs.com/package/react-native-calculator

There is an 'onAccept' prop with a data type: (value : number , text : string ) => void

I understand that this value / number is what I need to pass but I don't understand how to format my code to accommodate this. My code thus far is below where I am calling the acceptAdd function which will work with the passed value. I want to pass the calculator's value to acceptAdd. Thank you for any assistance.

Current Code:

onAccept = {acceptAdd}

Upvotes: 1

Views: 315

Answers (1)

iamcastelli
iamcastelli

Reputation: 1774

Since you haven't shared your detailed attempt, let's take assumptions from the lib you are using. Am assuming you are using a Functional Component, but this can be similar to a class component.

With TypeScript.



import React from 'react';
import { View } from 'react-native';
import { Calculator } from 'react-native-calculator';

// Lets Assume this is your calculator component
const App = (): JSX.Element => {
  // Create handler to handle your onAccept which mirror
  // the function signature from the docs.
  const acceptAdd = (value: number, text: string): void => {
    // Do whatever you want with the value.
    console.log({ value, text });
  };

  return (
    <View style={{ flex: 1 }}>
      <Calculator style={{ flex: 1 }} onAccept={acceptAdd} />
    </View>
  );
};

export default App;

Or in plain JavaScript



const App = () => {
  const acceptAdd = (value, text) => {
    // Do whatever you want with the value.
    console.log({ value, text });
  };

  return (
    <View style={{ flex: 1 }}>
      <Calculator style={{ flex: 1 }} onAccept={acceptAdd} />
    </View>
  );
};

Upvotes: 2

Related Questions