Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React dynamically added components not rendered

I’m dynamically adding instances of a custom (Kendo-React) component into an array in my main App.

The component:

    const PersonDD = () => {
      const ages = ["Child", "Adult", "Senior"];
      return (
        <div>
          <div>Person:</div>
          <DropDownList
            data={ages} style={{   width: "300px",  }} 
          />
        </div>
      );
    };

I’m adding one instance on initial render, and another two instances after the result from an Ajax call returns.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const SourceTab = (SourceTabProps) => {

     ....

  var componentList = [];
  componentList.push(<PersonDD/>);

  async function getStrata(){
    var url = '/access/.im.read';
    const res = await axios.get(  url  );
    console.log(res.data.item);
    componentList.push(<PersonDD/>);
    componentList.push(<PersonDD/>);
  }

  React.useEffect(() =>{
    getStrata();
  },[]);

  return (
    <Title title="People" />
     <div className='assignment_div_css'>
      {componentList}
     </div>);
};

The problem I have is that the one instance in the initial array are rendered, but the two created after the Ajax call are not rendered.

Do I need to call .render() or something similar to refresh?

>Solution :

You can simply use react useState to rerender component and in jsx map them.

like this :

const SourceTab = (SourceTabProps) => {


  const [componentList,setComponentList] = useState([PersonDD])
  

  async function getStrata(){
    var url = '/access/.im.read';
    const res = await axios.get(  url  );
    console.log(res.data.item);
    setComponentList([...componentList,PersonDD,PersonDD])

  }

  React.useEffect(() =>{
    getStrata();
  },[]);

  return (
    <Title title="People" />
  <div className='assignment_div_css'>
    {componentList.map((Component,index)=> <Component  key={index} />)}
  </div>);
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading