0

I'm building my own invoice/estimate generator with React.

I want to have a number of lines "product" equivalent to my state.

I wanted to do a loop and return my JSX. But I have no error, but my line product appears once only, and my state is set to 2.

Here is my try :

export default function ProductInformations(props: TProductInformations) {
    const [numberOfProducts, setNumberOfProducts] = useState<number>(2);

    const handleNumberOfProducts = (type: string) => {
        if (type === "add") return setNumberOfProducts(numberOfProducts + 1);
        if (type === "remove") return setNumberOfProducts(numberOfProducts - 1);
    };

    for (let i = 0; i <= numberOfProducts; i++) {
        return (
            // here is <p> with "price", "quantity", "name of the product"...
        );
    }
}

As the JSX is a bit long, I don't want to do a function that returns html and call the function in JSX.

Any idea why ?

Konrad
  • 21,590
  • 4
  • 28
  • 64
Johan
  • 2,088
  • 2
  • 9
  • 37

1 Answers1

0

Either push to an array

export default function ProductInformations(props: TProductInformations) {
    const [numberOfProducts, setNumberOfProducts] = useState<number>(2);

    const handleNumberOfProducts = (type: string) => {
        if (type === "add") return setNumberOfProducts(numberOfProducts + 1);
        if (type === "remove") return setNumberOfProducts(numberOfProducts - 1);
    };
    
    const products =[]
  
    for (let i = 0; i <= numberOfProducts; i++) {
        products.push(
            // here is <p> with "price", "quantity", "name of the product"...
        );
    }
  
    return <>{products}</>
}

or use map

export default function ProductInformations(props: TProductInformations) {
    const [numberOfProducts, setNumberOfProducts] = useState<number>(2);

    const handleNumberOfProducts = (type: string) => {
        if (type === "add") return setNumberOfProducts(numberOfProducts + 1);
        if (type === "remove") return setNumberOfProducts(numberOfProducts - 1);
    };
    
  
    return [...Array(numberOfProducts + 1)].map(() => /* here is <p> with "price", "quantity", "name of the product"... */)

}

Resources:

Konrad
  • 21,590
  • 4
  • 28
  • 64
  • So I guess `map` is the only way ? I can't just tell React to create this HTML element `state` number of times ? – Johan Jan 22 '23 at 17:58