Kane
Kane

Reputation: 615

Add the classes after 2 loops on react using map

I am trying to add the classes after 2 loops. It's working but can't hide {x++} text. How can hide this? I have also tried with using the index.

const workdata = this.state.worksData.map((work, index) => (
            <div
                className={
                    x % 3 == 0
                        ? "col-lg-4 col-md-6 offset-lg-0 offset-md-3"
                        : "col-lg-4 col-md-6"
                }
                key={index}
            >
                <div
                    className={
                        x % 3 == 0 ? "single-box" : "single-box with-line"
                    }
                >
                    <span>{work.position}</span>
                </div>
                {x++}
            </div>
        ));

using for loop and it works.

for (let i = 0; i < data.length; i++) {
        if (x % 3 == 0) {
            console.log("Class", data[i]);
        } else {
            console.log(data[i]);
        }
        x++;
    }

Upvotes: 0

Views: 71

Answers (1)

Mahesh More
Mahesh More

Reputation: 855

You should use existing index property instead of creating new x. Please see below sample code

const workdays = this.state.worksData.map((work, index) => (
            <div
                className={
                    (index + 1) % 3 == 0
                        ? "col-lg-4 col-md-6 offset-lg-0 offset-md-3"
                        : "col-lg-4 col-md-6"
                }
            >
                <div
                    className={
                        (index + 1) % 3 == 0 ? "single-box" : "single-box with-line"
                    }
                >
                    <span>{work.position}</span>
                </div>
            </div>
        ));

Upvotes: 2

Related Questions