Warm tip: This article is reproduced from serverfault.com, please click

How to change button color depending on array element in ReactJS

发布于 2020-11-28 03:50:02

Say I have two arrays like this:

state = {
   firstArr: ['one', 'two', 'three', 'four', 'five'],
   secondArr: ['one', 'three', 'four']
}

and I'm having a list of buttons like below:

{firstArray.map((item, index) => (
    <label className="btn btn-secondary" key={index}>
        <input type="checkbox" onChange={this.handleAddItem} value={item} /> {item}                              
    </label>
))}

How do I apply a different background color only to the buttons listed in the second array?

Questioner
Olawale Oladiran
Viewed
0
tanmay 2020-11-28 12:01:52

You need to have a conditional class like this, based on whether the current item is part of secondArr or not.

{firstArray.map((item, index) => (
    <label
        className={`btn btn-secondary ${secondArr.includes(item) ? 'different-bg-class' : ''}`}
        key={index}
    >
        <input type="checkbox" onChange={this.handleAddItem} value={item} /> {item}                              
    </label>
))}