4

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>
ethans33
  • 115
  • 1
  • 1
  • 8
  • This is what `props` good for. Also in `App.js` do ``. With calling the function directly, the return value of the `function` will be passed to `onPress`. – sonkatamas Dec 20 '20 at 23:39
  • @sonkatamas Can you show a code example? Cause the ```movePopUpCard``` is on a separate file and I don't think the button will be able to access it. – ethans33 Dec 21 '20 at 00:36

3 Answers3

3

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)
uday
  • 96
  • 5
1

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

halfer
  • 19,824
  • 17
  • 99
  • 186
Ashwith Saldanha
  • 1,700
  • 1
  • 5
  • 15
1

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

Nikhil bhatia
  • 1,297
  • 1
  • 8
  • 9