Like the title says, on mount I want to insert/append a Component, either as a child or sibling.
Things I’ve found online that haven’t worked:
ReactDOM.render()
- This replaces the whole node and its children with the
<Component />
.
- This replaces the whole node and its children with the
.insertAdjacentElement()
- I get the type error
Argument of type 'ReactNode' is not assignable to parameter of type 'Element'.
- I get the type error
.appendChild()
- I get the error
Argument of type 'JSX.Element' is not assignable to parameter of type 'Node'.
- I get the error
.append()
- I get error
Argument of type 'Element' is not assignable to parameter of type 'string | Node'.
- I get error
For example:
React.useEffect(() => {
// Code that makes <Component /> appear in DOM
}, []);
<div>
<div>
<p>Something</p>
{/* On mount <Component /> is inserted here */}
</div>
</div>
[Edited for more detail]:
I’m looking for a solution where I don’t have to enter anything inside of the return ();
.
All functionality to insert the <Component />
needs to be done above that.
3
Answers
You can use the
useState
hook to store an array of components in your state, and then use the map method to render them as children of another component. Inside theuseEffect
callback, you can use thesetState
function to update the array of components with a new component.For example:
You can see the whole example here: codesandbox.io
UPDATED ANSWER
I’m not sure this is the best solution but I think it can help you.
You can see the whole example here: codesandbox.io
You could handle it like this:
on/off
, and link it to a buttonnote that I am using:
Most of the methods listed are DOM api calls (
insertAdjacentElement
,appendChild()
etc.) The reason you’re getting all these type errors is because you can’t mix and match React and DOM elements like that. React uses it’s own virtual dom and doing something outside it’s rendering mechanisms is a huge anti-pattern.<Component />
although this looks like a DOM element, JSX actually compiles to function calls behind the scenes. You could potentially do something like this to render HTML directly in your effect.But this will not be treated as React and you’ll lose the state management functionality. The proper way to do this is to use a conditional in your
render()
method like the other answers suggested.