How would I call a function from another component in react native?

Viewed 7434

How would I call a function from another component?

App.js

<Button onPress={movePopUpCard()}></Button>
<PopUpCard/>

PopUpCard.js

const movePopUpCard = () => {
   //Code to update popUpCardX
}

<Animated.View style={[
    {transform: [{scale: scale}, {translateX: popUpCardX}]},
    {position: 'absolute'}
]}>
</Animated.View>
3 Answers

If you are using a functional component you have to use forwardRef to add reference to the component and useImperativeHandle to implement the method which you want to access through reference here is an example. Here I am calling bounce method which increases the scale of the component:

Snack: https://snack.expo.io/@ashwith00/adequate-salsa

Code:

App.js

export default function App() {
  const boxRef = React.useRef();
  return (
    <View style={styles.container}>
      <AnimatedBox ref={boxRef} />
      <Button title="Bounce" onPress={() => boxRef.current.bounce()} />
    </View>
  );
}

AnimatedBox.js

import React, { forwardRef, useImperativeHandle, useRef } from 'react';
import { View, Animated } from 'react-native';

export default forwardRef((props, ref) => {
  const scale = useRef(new Animated.Value(1)).current;
  useImperativeHandle(
    ref,
    () => ({
      bounce: () => {
        Animated.timing(scale, {
          toValue: 1.5,
          duration: 300,
        }).start(({ finished }) => {
          if (finished) {
            Animated.timing(scale, {
              toValue: 1,
              duration: 300,
            }).start();
          }
        });
      },
    }),
    []
  );
  return (
    <Animated.View
      style={{
        width: 100,
        height: 100,
        backgroundColor: 'red',
        transform: [{scale}]
      }}
    />
  );
});

By using ref and forwardRef you can achieve this. snack ex: https://snack.expo.io/@udayhunter/frisky-pretzels

App.js

import React,{useRef,useEffect} from 'react';
import { Text, View, StyleSheet } from 'react-native';
import PopUp from './PopUpCard'

const App =(props)=> {

const childRef = useRef(null)

  return (
    <View style={styles.container}>
    <PopUp ref={childRef}/>
    
    
    <Text
    onPress = {()=>{
    childRef.current.updateXvalue(10)
    }}
    >Press me</Text>
     
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
 
});

export default App

popUp.js

import React,{useState,useImperativeHandle,useEffect,forwardRef} from 'react'
import {View,Text,StyleSheet,Animated} from 'react-native'

const PopUp = (props,ref) => {
    const [xValue, setXvalue] = useState(10)
   
   const updateXvalue = (x)=>{
      setXvalue(prev=> prev+x)
      
    }
    
  useImperativeHandle(ref, () => ({
    updateXvalue
  }));

  return(
    <Animated.View style = {[styles.mainView,{transform:[{translateX:xValue}]}]}>
    </Animated.View> 
  )
}

const styles = StyleSheet.create({
  mainView : {
    height:100,
    width:100,
    backgroundColor:'red'
  }
})


export default forwardRef(PopUp)

move the function movePopUpCard to app.js

and pass in app.js pass it in

<PopUpCard movePopUpCard={(params) => movePopUpCard(params)}/>

you can call the function from PopUpCard component by this.props.movePopUpCard(params)

you can also pass params if requrired

Related