Search code examples
typescriptinterfacereact-typescript

React Native Typescript: Use functions inside interface and in components


how can i use function declared in interface inside FunctionComponent

interface IProps {
  someFunction(): Promise<boolean>;
}

const SomeClass: FC<IProps> = props => {
// Want to use somefunction method here how can i use this?? 
}

Also how can i call someFunction() from other component ?


Solution

  • Think of React component as a function which accepts some parameters. For example you can write a function which accepts another function:

    function logName(getName: () => string) {
       const name: boolean = getName();
       console.log(name);
    }
    

    And then you can call logName with any function which returns name, for example you can write:

    function getEnglishName() { return "John Doe"; }
    function getRussianName() { return "Ivan Ivan"; }
    
    logName(getEnglishName); // logs "John Doe" to console
    logName(getRussianName); // logs "Ivan Ivan" to console
    

    Notice how, when we called logName, we did not do logName(getEnglishName()) but we did logName(getEnglishName). That's because getEnglishName is a _function returning string, when it is called, but getEnglishName` is simply a string!

    Similarly to the above, React function components are just functions which accept something and return react components.

    Now, what React function accepts is commonly called "props". But you can simply think of it as argument to a function.

    So, in order to write a react component you have to define a function which accepts "something". In your case, that "something" is someFunction from IProps interface. However, it would be the caller which should give the real value of someFunction to your React component.

    First of all, you better use slightly different notation for IProps.

    interface IProps {
        someFunction: () => Promise<boolean>;
    }
    

    Then, I assume that you did import {FC} from 'react', and then you just can do what's below

    const FunctionComponent: FC<IProps> = props => {
      // This accesses "someFunction"
      props.someFunction
    }
    

    Since props object will contain everything you define in IProps, just like a regular object of type IProps

    Actually, since you have a Promise type, which means that someFunction is asynchronous, the proper full form would be

    const FunctionComponent: FC<IProps> = async props => {
      // This accesses "someFunction"
      const resultBoolean: boolean = await props.someFunction();
    }
    

    Now, somebody may use your component like this:

    // another file
    async function returnsBoolean(){
        return true; // return right away
    }
    
    
    // {} below means AnotherComponent needs no arguments
    const AnotherComponent: React.FC<{}>= () => {
       return ( <FunctionComponent someFunction={returnsBoolean} />);
    }