Skip to content
Advertisement

How to start a component in a loop and close it all 3 iterations

Hello i search solution for open tag in loop and close it all the 3 iteration. The goal is to create a grill based on container row and col. My problem is I do not know how to do.

Exemple :

    render(){
        const arrayName = ["john", "bob", "joe", "mat", "toto", "tata"]
        let arrayEl = [];
        let count = 1; 
          for ( let i = 0; i < arrayName.length; i++ ) {
             let name = arrayName[i]

             if (count === 1) {
                 arrayEl.push(<div className="row">);
                 arrayEl.push(<p className="col">{name}</p>);
                 count ++;
                 continue;
             }
             if (count === 3) {
                 arrayEl.push(<p className="col" >{name}</p>);
                 arrayEl.push(</div>);
                 count = 1;
                 continue;
             }
           }
        return (<div className="container">{arrayEl}</div>)
    }

and the result wanted is :

<div className="container">
    <div className="row">
        <div className="col">john</div>
        <div className="col">bob</div>
        <div className="col">joe</div>
    </div>
    <div className="row">
        <div className="col">mat</div>
        <div className="col">toto</div>
        <div className="col">tata</div>
    </div>
</div>

thank you for some help

EDIT

The problem is we can’t add someone element or componant without close it.

is Bad :

arrayEl.push(<div className="row">)

is good :

arrayEl.push(<div className="row"/>) or arrayEl.push(<div className="row"></div>)

Advertisement

Answer

I would change your data from:

 ["john", "bob", "joe", "mat", "toto", "tata"]
// to
 [["john", "bob", "joe"], ["mat", "toto", "tata"]]

Checkout https://lodash.com/docs/4.17.11#chunk for example of that

And then you can nest 2 .map to replicate the structure in JSX:

const chunk = (arr, chunckSize) => arr.reduce((chunks, value, index) => {
  const chunckIndex = Math.floor(index / chunckSize)
  const c = chunks[chunckIndex] || (chunks[chunckIndex] = [])
  c.push(value)
  return chunks
}, [])

render() {
    const arrayName = ["john", "bob", "joe", "mat", "toto", "tata"]

    return (
        <div className="container">
            {chunk(arrayName, 3).map(names => (
                <div className="row">
                    {names.map(name => <div className="col">{name}</div>)}
                </div>
            ))}
        </div>
    )
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement