今回は、label要素について書いてみます。
構成の考え方(Button / Input と同じ)
■label は <label> 要素
■表示テキストは、 children
■htmlFor などは HTML 標準 Props
Label.tsx
import React from "react"
export const Label = React.forwardRef<
HTMLLabelElement,
React.ComponentPropsWithRef<"label">
>(({ children, ...rest },ref)=>{
return (
<label
ref={ref}
{...rest}
style={{ display: "block", marginBottom: "4px" }}
>
{children}
</label>
)
});
使用例
Example.tsx
<Label htmlFor="email">メールアドレス</Label>
<Input id="email" type="email" />
FormField と組み合わせた例
FormField.tsx
import React from "react";
import { Input } from "../atoms/Input";
import { Label } from "../atoms/Label";
type FormFieldProps = {
label: string;
} & React.ComponentProps<typeof Input>;
export const FormField = ({ label, ...inputProps }:FormFieldProps)=>{
return (
<div style={{ marginBottom: "12px" }}>
<Label>{label}</Label>
<Input {...inputProps}/>
</div>
)
};
サイト
【React】Atomic Designでのコンポーネントの汎用性を上げる方法
