[React Bootstrap] Badge を表示してみる | 心を無にして始める React

今回は、Badge コンポーネントを表示します。
Badge コンポーネントは、特定の要素に注目を集めるために使います。アイコンやテキストをコンテンツに上付きまたは下付きで表示して、情報を明瞭に示すことができます。

準備
まだ components フォルダがなければ作ります。
src
を右クリックして New Folder
。

components と入力してフォルダを作ります。

今回は、components フォルダに Badge のコンポーネントを作って、表示してみます。
公式のドキュメントはここ。
https://react-bootstrap.github.io/components/badge/
Badge コンポーネントをつくる
component フォルダに Badge.js
を作ります。
Badge.js
を心を無にして編集してみます。
import React from 'react';
import { Badge as BootstrapBadge } from 'react-bootstrap';
function Badge(props) {
const {
bg,
pill,
children,
...otherProps
} = props;
return (
<BootstrapBadge bg={bg} pill={pill} {...otherProps}>
{children}
</BootstrapBadge>
)
}
export default Badge;
プロジェクトでは、コンポーネントを統一したデザインで利用することが多いです。
そのため、(React Bootstrap のコンポーネントをその場その場でカスタマイズしながら使うよりも、)プロジェクトでコンポーネントにしたものを使うほうが、変更をお手軽に漏れなくできることが多いです。
Badge コンポーネントを表示する
それでは、 App.js
を編集して Badge コンポーネントを表示します。
import './App.css';
import Badge from './components/Badge';
function App() {
return (
<div className="m-5">
<div className="mb-2">
<Badge variant="primary">
しかくいバッジ
</Badge>
</div>
<div>
<Badge variant="primary" pill>
角が丸いバッジ
</Badge>
</div>
</div>
);
}
export default App;
画面を確認してみます。

はい、できました。
余白(padding)を増やす
Badge.js
を編集してデザインを変えます。
上下の余白を少し増やして、文字も太字をやめます。
import React from 'react';
import { Badge as BootstrapBadge } from 'react-bootstrap';
function Badge(props) {
const {
bg,
pill,
children,
className,
...otherProps
} = props;
const _className = `py-2 fw-normal ${className || ''}`;
return (
<BootstrapBadge bg={bg} pill={pill} className={_className} {...otherProps}>
{children}
</BootstrapBadge>
)
}
export default Badge;
画面を確認してみます。

はい、できました。