skip to Main Content

Why it’s not working like that?

let elem = <div></div>
elem.appendChild(<h1>abc</h1>)

how I can add child to jsx element?

2

Answers


  1. You don’t have appendChild in JSX. You would directly add the element in:

    let elem = (
      <div>
        <h1>abc</h1>
      </div>
    );
    

    Or, you can use different components:

    import React from 'react';
    
    // Child component
    const ChildComponent = () => {
      return <h1>abc</h1>;
    };
    
    // Parent component
    const ParentComponent = () => {
      return (
        <div>
          <ChildComponent />
        </div>
      );
    };
    
    export default ParentComponent;
    
    Login or Signup to reply.
  2. React uses a virtual dom node, but appendChild can only work with real dom node.

    You can solve this in 2 ways.

    1. Use a real dom node instead of a react node.
    const ch = document.createElement("h1");
    ch.innerHTML = "abc";
    document.getElementById("parent").appendChild(ch);
    ...
    return <div id="parent"></div>;
    1. Use createRoot of "react-dom/client"
    import { createRoot } from "react-dom/client";
    ...
    createRoot(document.getElementById("parent")).render(<h1>abc</h1>);
    ...
    return <div id="parent"></div>;
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search