memoricab
memoricab

Reputation: 453

React add components dynamically from dynamically added component

What I am trying to do is to add components iteratively from the last dynamically added component.

|dynamically added component| ----on click----> |added new component| ---on click--> | added another component|

import React, { useState } from 'react';
import Product from '../../Product';
import Project from '../../Project';


const NewProject = () => {
    const [productList, setProductList] = useState([]);
    const addProduct = () => {
        setProductList([...productList, <Product addProduct={addProduct} key={productList.length}></Product>]);
    };

    return <React.Fragment>
        <Project addProduct={addProduct}>
        </Project>
        {productList}

    </React.Fragment>

}

export default NewProject; 

Basically, I'm passing addProduct const to the Product component and it executes the addProduct function again. I see addProduct is triggered but I don't see component came. I think I'm mixing some states there.

Adding Product component from Project component props works fine by the way. But I want to do the same with added product components.

Upvotes: 0

Views: 667

Answers (1)

DevAddict
DevAddict

Reputation: 2015

I don't know the exact problem but the way I use it is a little bit different instead of saving Product Component to the list, I only save the product data then I create a another function to render them into components and then pass it in return like below:

import React, { useState } from 'react';
import Product from '../../Product';
import Project from '../../Project';


const NewProject = () => {
    const [products, setProducts] = useState([{}]);
    
    const addProduct = () => {
        setProducts([...products, {}]);
    };

    const renderProducts = () => products.map((_, i) => <Product addProduct={addProduct}/>)

    return <>{renderProducts()}</>;
};

export default NewProject; 

Upvotes: 1

Related Questions