How to call parent component method from component/reactnode passed as props in React

Viewed 36

I am passing Button component as props of Toast component, so my custom button will be displayed inside toast component. If I click on button I need to call a method inside Toast component.

Toast usage:

const customActionButtonTemplate = ( 
<Mybutton label="Hide" onClick={// Here I wan t to call Toast components hideToast method//} />);

<Toast (...args)
customActionButtonTemplate = {customActionButtonTemplate()} />

Toast component:

export const Toast.FC<ToastInuts> = (props: ToastInputs ) => {
const hideToast(): void => {
   //toast clicked
}

return (
<div>
  <div>
    //contents
  </div>
  <div>
   {props.customActionButtonTemplate}
  </div>
</div>
)

};
1 Answers
const [hidden, setHidden] = useState(false);

const customActionButtonTemplate = ( 
<Mybutton label="Hide" onClick={()=>hideToast(!hidden)} />);

<Toast (...args, hidden)
customActionButtonTemplate = {customActionButtonTemplate()} />

You extract state, setHidden function will be passed to button that you want, and you will just pass value of hidden to Toast, based on which you will hide or not hide the Toast

Related