Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

225
Views
How to appendChild custom component using React JS and Typescript?

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
    </>
  )
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!