user18941960
user18941960

Reputation: 55

How to move a dom element from a child component to a parent component in React?

I have two components, a parent and a child.

Parent Component

const Parent = () => {
return (
<>
<div className="container"></div>
<div>more content</div>
<Child/>
</>
)
}

Child Component

const Child = () => {

const importantFunctionMustBeInChild = () => {
//Does a bunch of stuff that can't be done in the parent due to a lot of state that doesn't make sense to have in the parent
}

return (
<>
<button onClick={importantFunctionMustBeInChild}>Important Button</button>
</>
)
}

The problem is that I have a button in the child component. This button renders conditionally based off many different state toggles and has functions that can't be in the parent component because it wouldn't make sense to put it there and would take a long time to move all the state and functions up.

The issue is I now need to have the button to where the container div is in the parent component. Is there any way this can be done?

Upvotes: 0

Views: 700

Answers (1)

sid
sid

Reputation: 2027

Going by the logic, you can assign a value(string, object, array) to parent component's state in the child component, right? So why can you not assign a function to the state and run it on click in the parent?

Definetely you can! In your child, assign function as a reference to the parent's state and thats it!

useEffect(() => {
    // assign, don't invoke the function yet!
    setFunctionToExecute(() => importantFunctionMustBeInChild);
}, []);

Here's a complete working demo

Upvotes: 1

Related Questions