MaisyDoge13
MaisyDoge13

Reputation: 154

How to make bootstrap rows while going through a list in react and making elements

This is how I am currently doing it - it is very uneloquent, and it doesn't work. I am getting

TypeError: Cannot read property '0' of undefined
at grid.push(<Card key={index+x} name={list[index+x][0]} img={list[index+x][1]}/>);

this is my code

const list = // my list of data
        var grid = [];
        list.map((element, index) => {
            if (index%4 == 0) {
                if (index<list.length-2) {
                const el = (<div className="row">
                //card being a component I built
                <Card key={index} name={element[0]} img={element[1]}/>
                <Card key={index+1} name={list[index+1][0]} img={list[index+1][1]}/>
                <Card key={index+2} name={list[index+2][0]} img={list[index+2][1]}/>
                <Card key={index+3} name={list[index+3][0]} img={list[index+3][1]}/>
                </div>)
                grid.push(el);
                } else {
                    let remainder = (list.length-index);
                    for (var x=0;x+=1;x<remainder) {
                        grid.push(<Card key={index+x} name={list[index+x][0]} img={list[index+x][1]}/>);
                    }
                }

            }
        })\
        return (
        <div>
            {grid}
        </div>
        )

The current way I am doing it is making grid then iterating through the list and adding jsx to it. The problem is that I need to make a row for bootstrap every 4 columns to make the grid, any better ideas, solutions greatly appreciated!

Upvotes: 0

Views: 56

Answers (1)

Raju
Raju

Reputation: 86

You are using index+1, index+2, index+3 which will never exist in the array, when you reach last element. Instead calculate it in some other variable to find elements which exist.

Upvotes: 1

Related Questions