0

I have 2 nested screens in the navigator and I wish to use a function from one of those screens to another (from Screen1.js to Screen2.js). The function I want to call in Screen2.js is addList(). This is the Screen1.js

export default function Screen1({navigation}){
   //...

  function addList (list){
   //Code...
   };

  //...
}

I have tried to import the function addList and use it like this in Screen2:

import addList from './Screen1

//...

export default function Screen2({navigation}){
  //...

  function createSomething(){
    //...   
    addList(list);
    //...         
  }

  //...
}

However, my attempt was unsuccessful. How can I perform to do this?

Tiago
  • 121
  • 2
  • 9

2 Answers2

0

addList should be in the parent component. This way you can pass the function as props in screen1 and screen2.

JB_DELR
  • 737
  • 1
  • 4
  • 7
  • Do you mean the addList function should be outside of the Screen1 function? And then passing the state required as props? – Tiago Sep 05 '20 at 13:46
  • yes, it's my solution without use refs. But Ajmal Hasan solution is good too. – JB_DELR Sep 06 '20 at 13:58
0

If I do what you want with Ajmal solution, I think it should be:

import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef } from 'react'

const { forwardRef, useRef, useImperativeHandle } = React;
    
    // We need to wrap component in `forwardRef` in order to gain
    // access to the ref object that is assigned using the `ref` prop.
    // This ref is passed as the second parameter to the function component.
    const Screen1 = forwardRef((props, ref) => {
    
      // The component instance will be extended
      // with whatever you return from the callback passed
      // as the second argument
      useImperativeHandle(ref, () => ({
    
        addList() {
          alert("getAlert from Child");
        }
    
      }));
    
      return <h1>Hi</h1>;
    });

    const Screen2 = (props) => {
      return (
       <div>
         ....
         <button onClick={(e) => props.screen1Ref.addlist(...)}>addList</button>
       </div>
      )
    }
    
    const Parent = () => {
      // In order to gain access to the child component instance,
      // you need to assign it to a `ref`, so we call `useRef()` to get one
      const screen1Ref = useRef();
    
      return (
        <div>
          <Screen1 ref={screen1Ref} />
          <Screen2 screen1Ref={screen1Ref} />
        </div>
      );
    };
    
    ReactDOM.render(
      <Parent />,
      document.getElementById('root')
    );

Now, in screen2 you can call props.screen1Ref.addList(...)

JB_DELR
  • 737
  • 1
  • 4
  • 7