reactjsreact-portal

firing a function that is in the parent component from a React.CreatePortal component


I have a parent component that has a button, when clicked, opens a new component inside a React.CreatePortal control.

On that CreatePortal component, I have a button like this:

return (
        ReactDOM.createPortal(
            <div id="portal_Game">
            <div><button onClick={jump}> JUMP </button></div>

But the 'jump' function is on the parent control.

In the portal, it's not recognized.

Is there a way to fire the 'jump' on the parent from the portal?

Thanks!


Solution

  • Pass the jump function as a prop to the child component like this:

    In the parent component pass the jump function:

    ...
    <Child jump={jump} />
    ...
    

    You can use the function in the child component via props:

    ...
    <button onClick={props.jump}> JUMP </button>
    ...