Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 484
ethans33 Avatar asked Sep 19 '25 02:09

ethans33


1 Answers

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)
like image 107
uday Avatar answered Sep 21 '25 21:09

uday