Home > Mobile >  Rendering a div element inside existing div during page rendering
Rendering a div element inside existing div during page rendering

Time:02-06

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>
            }
        </>
    );

CodePudding user response:

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);

CodePudding user response:

This is a little ambiguous. But, if I am understanding correctly, I think you can set the innerHTML to append the div

parentDiv.innerHTML  = "<div>Your div content here</div>"

better yet, set your div as a variable and then just = the variable for cleaner code.

const myDiv = "<div>Your div content here</div>"
parentDiv.innerHTML  = myDiv

Used this to make sure I was remembering correctly

  • Related