0

I'm trying to inject an already existing element on the page into my react DOM in order to wrap around it.

Something like:

var someElement = document.getElementById("stuff")
var parent = someElement.parentNode;
var wrapper = document.createElement("div");
wrapper.id = "root1";
parent.replaceChild(wrapper, someElement);
wrapper.appendChild(someElement);

ReactDOM.render(
      <Wrapper child="{{someElement}}" />,
      document.getElementById("root1")
    );

I'm not sure how I can go about injecting the element into react + I need the styles of the element to stay as is.

1 Answer 1

2

You could use React's dangerouslySetInnerHTML method like so:

function getHtml(){
    return "<h1>Hello World</h1>" // element.innerHTML (optional)
}


ReactDOM.render(
      <Wrapper> 
           <div dangerouslySetInnerHTML={{ __html: getHtml() }} />
     </Wrapper>,
      document.getElementById("root1")
    );

To add: <Wrapper/> should render { this.props.children }

Documentation here: https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.