0

I have a containerElement and a react component. I want to add the react component into the containerElement. Is there a way I can do it? I have tried containerElement .appendChild(), but not working.

const containerElement = document.getElementById(divId);
React component: <ReactComponent></ReactComponnet>
1

2 Answers 2

2
ReactDOM.render(<ReactComponent/>, document.getElementById(divId));
Sign up to request clarification or add additional context in comments.

1 Comment

You also need to import ReactDOM from "react-dom" or similar.
1

Following the React lifecycles, you shouldn't have to insert the component into your parent component (containerElement). The react component should be inserted in the normal flow as a child or grandchild of the parent component.

If I'm understanding your question correctly, you need to handle the case where you are getting the DOMElement outside the normal flow of the React lifecycle. For that you can use refs.

For example below, define the component you're trying to insert somewhere in the render lifecycle of your container. No matter how nested the child is, you can "get" the child DOM element just like you are trying to do with document.getElementById from your question.

class Parent extends React.Component {
   constructor(props) {
      super(props);
      this.myRef = React.createRef();
   }

   render() {
      return (
         <FunctionComponent ref={this.myRef} />
      );
   }
}

Hope this helps

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.