javascripthtmlreactjsreact-16

Rendering a div element inside existing div during page rendering


I'm stuck at rendering a component insider a div. My code is like below, I want to render the div with classname RequestNewOrgBtn inside the parentDiv. How can I do it at runtime of render?

const labelItem =  Array.from(document.querySelectorAll('label'))
        .find(el => el.textContent === 'External Org Name');
    const parentDiv =  labelItem?.parentNode?.parentNode?.parentNode;

    return(
        <>
            {
                
              //render below div inside parentDiv
                <div className="RequestNewOrgBtn">
                    <Button disabled={false} onClick={onAddClick}>
                        { "Request New External org" }
                    </Button>
                    <RequestExternalOrgModal
                        isOpen={ShowReqExOrgModal}
                        onClose={onReqExOrgModalClose} />
                </div>
            }
        </>
    );

Solution

  • Probably the easiest way to do this would be to render the appropriate parts of your React app into the element in question, similar to how you would render <App /> into your root element.

    For example...

    import { createRoot } from "react-dom/client";
    
    import RequestNewOrgBtn from "./RequestNewOrgBtn"; // your component
    
    const labelItem = Array.from(document.querySelectorAll("label")).find(
      (el) => el.textContent === "External Org Name"
    );
    const parentDiv = labelItem?.parentNode?.parentNode?.parentNode;
    
    if (parentDiv) {
      // create a new root for your button component
      const btnRootElement = document.createElement("div");
    
      // append it into the found `parentDiv`
      parentDiv.appendChild(btnRootElement);
    
      const btnRoot = createRoot(btnRootElement);
      btnRoot.render(<RequestNewOrgBtn />);
    }
    

    Edit unruffled-carson-0qtcfc


    For React 16, you just use the ReactDOM equivalent

    import ReactDOM from "react-dom";
    
    // ...
    
    ReactDOM.render(<RequestNewOrgBtn />, btnRootElement);