1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

hookを使ったMaterialUIのハートアイコンのON・OFF

Last updated at Posted at 2021-01-29

 MaterialUIを使って、ハートアイコン(MaterialUI的にはFavoriteIcon)を
実装したいときに色々悩んだので書きます。

##結論
####完成品
ezgif.com-gif-maker.gif

####コード

import { React, useState } from "react";
import { IconButton } from "@material-ui/core";
import FavoriteIcon from "@material-ui/icons/Favorite";
import FavoriteBorderIcon from "@material-ui/icons/FavoriteBorder";


const Demo = () => {

//ハートの状態を管理するfavoを定義(初期値はfalse)
  const [favo, setFavo] = useState(false);

//アイコンをクリックしたらfavoのtrueとfalseが切り替わる関数を作成
const handleClick = () => {
  if (favo === false) {
      setFavo(true);
    } else {
      setFavo(false);
    }
  };

//trueなら<FavoriteBorderIcon  />をfalseなら<FavoriteIcon color={"secondary"} />を描画
return(
 <>
      <IconButton
        onClick={() => handleClick()}
      >
        {favo ? <FavoriteIcon color={"secondary"} /> : <FavoriteBorderIcon />}
      </IconButton>
 </>
)
}
export default Demo

ハートの色を白から赤に変えるために
FavoriteIconにはcolor={"secondary"}を与えている。
##感想

可読性はあんまり良くないです。
もっといい方法知っている方は教えていただけると助かります!:heart_eyes:

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?