-2

I write all functional components, now I want to call a child component method in parent component. is it possible or not? If yes, Please give me some direction to do it.Thanks in advance.

import React, { useRef } from 'react';
import ChildOne from './child_one'
import ChildTwo  from './child_two'

function ParentComponent(props) {

  const childRef = useRef();

  const onTabChange = (e,{activeIndex})=> {
    console.log(childRef)
  }

  let panes = [
   {menuItem: 'ChildOne', render: () => <Tab.Pane  attached={false}> 
     <ChildOne ref={childRef}/></Tab.Pane>},
   {menuItem: 'ChildTwo', render: () => <Tab.Pane attached={false}> 
     <ChildTwo/> </Tab.Pane>},
  ]

  return(

   <Tab menu={{secondary:true, pointing:true}} panes={panes} 
    onTabChange={onTabChange}/>
 )
}
export default ParentComponent;

child 1

import React, { forwardRef, useImperativeHandle } from 'react';

export default function Child1Component forwardRef((data,ref) => {

updateData = () =>{
    console.log(update data)
}


ref={updateData}
return(
    <h1>Child one</h1>
)
})

child2

import React from 'react'
export default function Child2Component (data) => {return(<h1>Child Two</h1>)}

I tried with above code, but getting getAlert not a function.

neelima
  • 461
  • 10
  • 25
  • 1
    Please include what you've tried in the question – Gihan Apr 17 '20 at 06:18
  • 2
    Does this answer your question? [Call child method from parent](https://stackoverflow.com/questions/37949981/call-child-method-from-parent) – Super Hornet Apr 17 '20 at 06:25
  • Without seeing any code I'm inclined to say no. If the function belongs to the child then generally only the child component, or descendants of the child the function is passed to, can call it. Children can invoke functions passed to them as props. Please include a [Minimal, Complete, and Reproducible](https://stackoverflow.com/help/minimal-reproducible-example) example of your code. – Drew Reese Apr 17 '20 at 06:25
  • I am asking for function components, but here only class component example and reference, I didn't understand. give me solution in functional components. thanks – neelima Apr 17 '20 at 06:43

1 Answers1

0

You can use refs to do that. https://reactjs.org/docs/refs-and-the-dom.html

Check out this example: https://codesandbox.io/s/exposing-functions-through-ref-cxx6t

Tom Slutsky
  • 684
  • 6
  • 11