Home > Net >  How to appendChild custom component using React JS and Typescript?
How to appendChild custom component using React JS and Typescript?

Time:11-30

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!

CodePudding user response:

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>
    </>
  )
}
  • Related