reactjsreact-nativereact-functional-component

React Native doesn't respect the function scope


I am developing a react-native app. Recently, I encountered a strange behavior of functional components. Typically, I break large component into smaller components, write separate logic for each smaller component, and then call them in the same component.

In the below code, I have not defined the method onPressed in the SmallComponentB but when I click on this it calls the method from SmallComponentA

const SmallComponentA = ({}) => {

    onPressed = () => alert('Clicked A')

    return <Text onPress={onPressed} >Press On A</Text>
}

const SmallComponentB = ({}) => {
    return <Text onPress={onPressed} >Press On B</Text>
}

const ActualComponent = ({}) => {
    return(
        <>
        <SmallComponentA />
        <SmallComponentB />
        </>
    )
}

Solution

  • You can do it both ways, either it's a separate function in each or it should be a common function

    With Separate:

        const SmallComponentA = ({}) => {
            const onPressed = () => alert('Clicked A')
        
            return <Text onPress={onPressed} >Press On A</Text>
        }
        
        const SmallComponentB = ({}) => {
            const onPressed = () => alert('Clicked B')
        
            return <Text onPress={onPressed} >Press On B</Text>
        }
        
        const ActualComponent = ({}) => {
            return(
                <>
                <SmallComponentA />
                <SmallComponentB />
                </>
            )
        }
    

    Common Function:

        const onPressed = ( component ) => alert('Common Clicked '+ component);
        
        const SmallComponentA = ({}) => {
          return <Text onPress={()=>onPressed("A")}>Press On A</Text>;
        };
        
        const SmallComponentB = ({}) => {
          return <Text onPress={()=>onPressed("B")}>Press On B</Text>;
        };
        
        const ActualComponent = ({}) => {
          return (
            <>
              <SmallComponentA />
              <SmallComponentB />
            </>
          );
        };
    

    Hope it will hep you!