Home > database >  passing function between separate components in react not between child and parent
passing function between separate components in react not between child and parent

Time:07-21

I have a small question regarding passing functions between components that are not in parent/child relationship. My structure inside App.

function App() {
  return (
    <div className="App">
      <Header/>
      <Pfl />
      <Sdc/>
      <Checkscan/>
    </div>
  );
}

Those 3 components have an on click function attached to a button i want the button from the pfl component to trigger all 3 on click functions. When i click on the button in the pfl component i want to trigger the function running in the pfl component and the functions that are inside the Sdc,Checkscan component. Whats the best way to do it and pass the functions from the other components so when i click the button inside the pfl component it will trigger all the methods from the other 2 components(Sdc,Checkscan)?

Or if I make a container that looks like this

export default function Apicontainer() {
    return (
        <React.Fragment>
            <Pfl />
            <Sdc />
            <Checkscan />
            <Button variant="contained">Start</Button>
        </React.Fragment>
    )
}

and in app.js i only have the Apicontainer.

How do i transfer all the functions to work in that button click Component

CodePudding user response:

I just wrote some quick and dirty example code to show how you can share things between components via a parent component:

export default function Apicontainer() {
  const [sharedState, setSharedState] = useState({sdc: null, checkScan: null})

  function pflFunction() {
    console.log('pflFunction')
    // do your stuff here. I would update state with some reasonable data, and then pass 
    // the relevant data to the component that needs it. This is just an example.
    setSharedState({sdc: 'sdcData', checkScan: 'checkScanData'})
  }
  return (
    <React.Fragment>
      <Pfl onClick={pflFunction} />
      <Sdc data={sharedState.sdc}/>
      <Checkscan data={sharedState.checkScan} />
      <Button variant="contained">Start</Button>
    </React.Fragment>
  )
}

// Example of how to trigger a function inside a component (separate file):

export default function Sdc({data}){

  const sdcFunction = useCallback(() => {
    // implement the function you want to call here. useCallback makes sure to keep
    // a stable reference to the function, so that you can rely on it in a useEffect
  }, [])

  useEffect(() => {
    if(data){
      // do something. This effect will run whenever the data or sdcFunction changes.
      sdcFunction()
    }
  }, [data, sdcFunction])

  return (
    <div>your Sdc view code here</div>
  )
}

For the record: If fplFunction is anything else than an onClick handler, you should make sure the function has a stable reference, using useCallback (as in the last component)

  • Related