Search code examples
reactjsstyled-components

Is it possible to use a loop to insert several created components into one block


    <PSmall>
        <img src={images[1]} />
        <img src={images[2]} />
        <img src={images[3]} />
    </PSmall>

we have a styled component PSmall. It is necessary to make dynamic imgs instead of statically created ones, the number of which will depend on the number of elements in the image array. I.e. I receive an array with 5 elements and 5 img elements with the images[i] attribute should appear. One possible way is to create div and apply background img to them. but how to set src then. and how to choose the right path for them.\

const CreateDiv = (array:string[]) => { 
    if(array.length > 1){
        for (let i =1; i<(array.length-1); i++){
            let create = document.createElement('div');
            create.className='img';
            document.appendChild(create);
        }
    }

Solution

  • let create = document.createElement('div'); Its a JavaScript code. In React it seen as evil!

    React combines JavaScript and Html into one - JSX. Instead just use <div></div>.

    For loops, use .map instead of foreach in case of rendering or processing arrays without needing an index.

    So if you want a method to return a Div just use const CreateDiv = () => <div>// ur code //</div>

    If you want to map an array to create divs for each new array parameter, for some reason, you can achieve it like so

    const CreateDiv = (array) => array.map((item) => <div {...item}>// ur code //</div>)

    NOTE in this case array is assuming you are passing some parameters for each new Div.

    Regardless, Just use .map for mapping and <div> to return it. Same goes for any other component, or element, instead of div