Help us understand the problem. What is going on with this article?

Reactで特定の条件を満たす行の背景色を変えたい

やりたいこと

値により行の背景を変えたい。ここではgenderがfemaleならピンクにする。
下記のような感じ。

スクリーンショット 2019-12-03 13.15.05.png

基本方針?

基本的には条件に応じて三項演算子等を使ってstyleやclassNameを切り替えるのが基本。

条件 ? A : B;

条件がtrueならA、falseならBを実行。

CSSを切り替える

まず、CSSを切り替えてみる。
ループにて表を描画しながら、genderがfemaleなら背景を変えるような操作。

<tbody>
    {
        this.state.listData.map(member => (
            <tr key={member.docId} style={member.gender === "female" ? { background: "#ffe4e1" } : {}}>
                <td>{member.docId}d</td>
                <td>{member.email}</td>
                <td>{member.gender}</td>
                <td><img src={member.avatarUrl} height="30" width="30" alt="" /></td>
                <td><Link to={`/show/${member.docId}`}><Button size="sm" color="primary">詳細</Button></Link></td>
                <td><Link to={`/edit/${member.docId}`}><Button size="sm" color="success">編集</Button></Link></td>
            </tr>
        ))
    }
</tbody>

Classを切り替える

classの場合も基本は同じ。

あらかじめ、

.female {
  background: #ffe4e1;
}

のようなcssが定義されているものとして、下記のようにclassを切り替える。

<tbody>
    {
        this.state.listData.map(member => (
            <tr key={member.docId} className={member.gender === "female" ? "female" : null}>
                <td>{member.docId}d</td>
                <td>{member.email}</td>
                <td>{member.gender}</td>
                <td><img src={member.avatarUrl} height="30" width="30" alt="" /></td>
                <td><Link to={`/show/${member.docId}`}><Button size="sm" color="primary">詳細</Button></Link></td>
                <td><Link to={`/edit/${member.docId}`}><Button size="sm" color="success">編集</Button></Link></td>
            </tr>
        ))
    }
</tbody>

なお、もっとエレガントにclass名を制御したい場合は、こちらの記事が参考になります。
以上。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした