發布於 2023-03-15

更新於 2023-03-18

程式

約458字 (3分鐘閱讀)

[Day 23] 在 React 中快速加入 Font Awesome - 嘗試 30 日寫文充版挑戰

Title Image

Photo by Font Awesome on Font Awesome

前言 - Prologue

嘗試寫 30 天文充實版面 (跳過假日 ლ(́◕◞౪◟◕‵ლ) ) 更新文章的 Day 23

在現今這個設計注重視覺效果的時代, icon 已經成為許多網站和應用程式中不可或缺的元素之一。而 Font Awesome 就是一個廣泛使用的矢量 icon 庫,提供了豐富的 icon 選擇和彈性的應用方式。

本篇文章將介紹如何在 React 專案中安裝 Font Awesome 套件,並使用 <FontAwesomeIcon> 元件來呈現矢量 icon,讓網站或應用程式擁有更多元化的視覺效果。

可參考官方文件:React | Font Awesome Docs

正文 - Main text

透過以下步驟安裝 Font Awesome 圖示庫:

1. 在 React 專案中安裝 Font Awesome 套件可以使用 npmyarn 安裝:

# 使用 npm 安裝
npm install @fortawesome/fontawesome-free

# 使用 yarn 安裝
yarn add @fortawesome/fontawesome-free

2.index.js 檔案中引入 Font Awesome 的 CSS 樣式表:

import '@fortawesome/fontawesome-free/css/all.css';

3. 在需要使用 Font Awesome 圖示的元件中引入所需的圖示。例如,如果想在 Button 元件中使用一個 heart 圖示,可在 Button.js 檔案中進行引入:

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faHeart } from '@fortawesome/free-solid-svg-icons';

function Button() {
  return (
    <button>
      <FontAwesomeIcon icon={faHeart} />
      Like
    </button>
  );
}

4. 完成以上步驟後,就可以使用 Font Awesome 圖示了。

在 React 中,通常不建議使用 <i> 標籤來顯示 icon,因為這個標籤是用來表示斜體的文字,而不是 icon。相反的,建議使用 Font Awesome 提供的 <FontAwesomeIcon> 元件,或其他的 icon 庫提供的元件,例如 React Icons 的 <Icon> 元件。

後記 - Epilogue

本文源自可參照 [Day 22] 如何在 React 實現滑動返回頂部按鈕 - 嘗試 30 日寫文充版挑戰 所使用到的 icon 衍生如何引用 Font Awesome Icon。

[Day 23] 在 React 中快速加入 Font Awesome - 嘗試 30 日寫文充版挑戰

https:///blog/42

作者

Kama

Read more from 程式
lightbox-image
Toggle Button - Red Pandas Icons by svgrepo.com

Copyrights © 2023 Kama, All Rights Reserved.