Kong Konfus
Kong Konfus

Reputation: 87

How to append JSX to DOM in React?

I want to append something to my DOM.

let parent = document.getElementById("TabContainer");
let settings = 
<Box id="test">
  <GlobalSettings activeTab={"test"}></GlobalSettings>
</Box>
                
parent.appendChild(settings);

I get the following error

Argument of type 'Element' is not assignable to parameter of type 'Node'.
  Type 'Element' is missing the following properties from type 'Node': baseURI, childNodes, firstChild, isConnected, and 47 more.

Box is a normal div and GlobalSettings is my own component. I know it's maybe bad practice to manipulate the DOM like this, but for me it seems to be an easy way. Btw this code runs in the onClick function from a Button.

I hope someone can help me :)

Thx

Upvotes: 6

Views: 12959

Answers (2)

Volfra
Volfra

Reputation: 114

React 18 warns that you need to use createRoot instead.

You can fix it by replacing ReactDom.render with this:

import { createRoot } from 'react-dom/client';

createRoot(parent).render(settings)

Upvotes: 2

Riwen
Riwen

Reputation: 5190

JSX is only syntactic sugar; despite its appearance, it's not HTML, it's JavaScript. You can "append" something into your DOM using ReactDOM.render.

Edit: you're probably better off using portals; this is exactly what they are for.

Upvotes: 2

Related Questions