skip to Main Content

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 />
        </>
    )
}

2

Answers


  1. So you can individually set the onPressed function inside each of the individual arrow function like,

    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 />
            </>
        );
    }
    Login or Signup to reply.
  2. You can do it both ways, either it’s a separate function in each or it should be a common function

    1. 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 />
               </>
           )
       }
      
    2. Common Function

      const onPressed = ( component ) => alert(‘Common Clicked ‘+ component);

      const SmallComponentA = ({}) => {
      return <Text onPress={()=>onPressed("A")}>Press On A;
      };

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

      const ActualComponent = ({}) => {
      return (
      <>

      </>
      );
      };

    Hope it will hep you!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search