1

I have some code like

const ParentComponent = () => {
  let child = <ChildComponent {...props} />;
  if (condition) {
    const parent = document.GetElementById("parentId");
    //Here is a problem
    parent.appendChild(child);
  }
  return (
    <>
      <div id="parentId"></div>
    </>
  );
};
export default ParentComponent;

const ChildComponent = () => {
  return (
    <>
      <div></div>
    </>
  );
};
export default ChildComponent;

I want to dynamically add child components multiple times but getting an error enter image description here

I am happy to do it in any way using Javascript or useRef. Thanks!

2
  • 2
    The main problem is you shouldn't be mixing React with native DOM methods like that. Commented Nov 28, 2021 at 22:04
  • 1
    Is there a reason why you're not using JSX to conditionally render the element instead? Even if you want to do it through native DOM methods, you have several issues: (1) you have a typo in your document.GetElementById (it should be lowercase 'g', (2) you are not waiting for the virtual DOM to be rendered (and be available in the real DOM) before appending it. See useEffect. Commented Nov 28, 2021 at 22:25

1 Answer 1

1

The standard way to do conditional rendering in react is as follows:

const ParentComponent = () => {
  return (
    <>
      <div id="parentId">
        {condition && <ChildComponent {...props } />}
      </div>
    </>
  );
};
export default ParentComponent;

You mentioned wanting to do it multiple times, though you didn't show an example of what you have in mind. You can create an array and fill it with however many child elements you want. For example:

const ParentComponent = () => {
  const [childCount, setChildCount] = useState(8);

  const children = [];
  for (let i = 0; i < childCount; i++) {
    if (condition) {
      children.push(<ChildComponent {...props } />);
    }
  }

  return (
    <>
      <div id="parentId">
        {children}
      </div>
    </>
  )
}
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.