체크박스
체크박스 (Checkbox)
체크박스는 사용자가 항목 집합(set)에서 하나 또는 여러 개의 항목을 선택할 수 있게 해 주는 컴포넌트예요. 옵션을 켜거나 끄는 데 사용할 수 있답니다. 목록에 여러 옵션이 있다면 on/off 스위치 대신 체크박스를 사용해 공간을 절약할 수 있어요. 옵션이 하나뿐이라면 체크박스보다는 on/off 스위치를 사용하는 게 좋아요.
출처: 문서
본문
기본 체크박스 (Basic checkboxes)
import Checkbox from '@mui/material/Checkbox';
const label = { slotProps: { input: { 'aria-label': 'Checkbox demo' } } };
export default function Checkboxes() {
return (
<div>
<Checkbox {...label} defaultChecked />
<Checkbox {...label} />
<Checkbox {...label} disabled />
<Checkbox {...label} disabled checked />
</div>
);
}
라벨 (Label)
FormControlLabel 컴포넌트 덕분에 Checkbox에 라벨을 제공할 수 있어요.
import FormGroup from '@mui/material/FormGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
export default function CheckboxLabels() {
return (
<FormGroup>
<FormControlLabel control={<Checkbox defaultChecked />} label="Label" />
<FormControlLabel required control={<Checkbox />} label="Required" />
<FormControlLabel disabled control={<Checkbox />} label="Disabled" />
</FormGroup>
);
}
크기 (Size)
size prop을 사용하거나 svg 아이콘의 폰트 크기를 커스터마이징해서 체크박스의 크기를 변경할 수 있어요.
import Checkbox from '@mui/material/Checkbox';
const label = { slotProps: { input: { 'aria-label': 'Checkbox demo' } } };
export default function SizeCheckboxes() {
return (
<div>
<Checkbox {...label} defaultChecked size="small" />
<Checkbox {...label} defaultChecked />
<Checkbox
{...label}
defaultChecked
sx={{ '& .MuiSvgIcon-root': { fontSize: 28 } }}
/>
</div>
);
}
색상 (Color)
import { pink } from '@mui/material/colors';
import Checkbox from '@mui/material/Checkbox';
const label = { slotProps: { input: { 'aria-label': 'Checkbox demo' } } };
export default function ColorCheckboxes() {
return (
<div>
<Checkbox {...label} defaultChecked />
<Checkbox {...label} defaultChecked color="secondary" />
<Checkbox {...label} defaultChecked color="success" />
<Checkbox {...label} defaultChecked color="default" />
<Checkbox
{...label}
defaultChecked
sx={{
color: pink[800],
'&.Mui-checked': {
color: pink[600],
},
}}
/>
</div>
);
}
아이콘 (Icon)
import Checkbox from '@mui/material/Checkbox';
import FavoriteBorder from '@mui/icons-material/FavoriteBorder';
import Favorite from '@mui/icons-material/Favorite';
import BookmarkBorderIcon from '@mui/icons-material/BookmarkBorder';
import BookmarkIcon from '@mui/icons-material/Bookmark';
const label = { slotProps: { input: { 'aria-label': 'Checkbox demo' } } };
export default function IconCheckboxes() {
return (
<div>
<Checkbox {...label} icon={<FavoriteBorder />} checkedIcon={<Favorite />} />
<Checkbox
{...label}
icon={<BookmarkBorderIcon />}
checkedIcon={<BookmarkIcon />}
/>
</div>
);
}
제어(Controlled) 체크박스
checked와 onChange props로 체크박스를 제어할 수 있어요:
import * as React from 'react';
import Checkbox from '@mui/material/Checkbox';
export default function ControlledCheckbox() {
const [checked, setChecked] = React.useState(true);
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setChecked(event.target.checked);
};
return (
<Checkbox
checked={checked}
onChange={handleChange}
slotProps={{
input: { 'aria-label': 'controlled' },
}}
/>
);
}
불확정 상태 (Indeterminate)
체크박스 입력은 폼에서 두 가지 상태만 가질 수 있어요: checked(체크됨) 또는 unchecked(체크 안 됨)예요. 체크된 값이 제출되거나 제출되지 않거나 둘 중 하나죠. 시각적으로는 체크박스가 가질 수 있는 상태가 세 가지예요: checked, unchecked, 그리고 indeterminate(불확정)입니다. indeterminateIcon prop을 사용해 불확정 상태의 아이콘을 변경할 수 있어요.
import * as React from 'react';
import Box from '@mui/material/Box';
import Checkbox from '@mui/material/Checkbox';
import FormControlLabel from '@mui/material/FormControlLabel';
export default function IndeterminateCheckbox() {
const [checked, setChecked] = React.useState([true, false]);
const handleChange1 = (event: React.ChangeEvent<HTMLInputElement>) => {
setChecked([event.target.checked, event.target.checked]);
};
const handleChange2 = (event: React.ChangeEvent<HTMLInputElement>) => {
setChecked([event.target.checked, checked[1]]);
};
const handleChange3 = (event: React.ChangeEvent<HTMLInputElement>) => {
setChecked([checked[0], event.target.checked]);
};
const children = (
<Box sx={{ display: 'flex', flexDirection: 'column', ml: 3 }}>
<FormControlLabel
label="Child 1"
control={<Checkbox checked={checked[0]} onChange={handleChange2} />}
/>
<FormControlLabel
label="Child 2"
control={<Checkbox checked={checked[1]} onChange={handleChange3} />}
/>
</Box>
);
return (
<div>
<FormControlLabel
label="Parent"
control={
<Checkbox
checked={checked[0] && checked[1]}
indeterminate={checked[0] !== checked[1]}
onChange={handleChange1}
/>
}
/>
{children}
</div>
);
}
:::warning
indeterminate가 설정되면 checked prop의 값은 제출되는 폼 값에만 영향을 줍니다. 접근성이나 UX에는 영향을 미치지 않아요.
:::
FormGroup
FormGroup은 선택 제어 컴포넌트들을 묶는 데 사용되는 유용한 래퍼예요.
import * as React from 'react';
import Box from '@mui/material/Box';
import FormLabel from '@mui/material/FormLabel';
import FormControl from '@mui/material/FormControl';
import FormGroup from '@mui/material/FormGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormHelperText from '@mui/material/FormHelperText';
import Checkbox from '@mui/material/Checkbox';
export default function CheckboxesGroup() {
const [state, setState] = React.useState({
gilad: true,
jason: false,
antoine: false,
});
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setState({
...state,
[event.target.name]: event.target.checked,
});
};
const { gilad, jason, antoine } = state;
const error = [gilad, jason, antoine].filter((v) => v).length !== 2;
return (
<Box sx={{ display: 'flex' }}>
<FormControl sx={{ m: 3 }} component="fieldset" variant="standard">
<FormLabel component="legend">Assign responsibility</FormLabel>
<FormGroup>
<FormControlLabel
control={
<Checkbox checked={gilad} onChange={handleChange} name="gilad" />
}
label="Gilad Gray"
/>
<FormControlLabel
control={
<Checkbox checked={jason} onChange={handleChange} name="jason" />
}
label="Jason Killian"
/>
<FormControlLabel
control={
<Checkbox checked={antoine} onChange={handleChange} name="antoine" />
}
label="Antoine Llorca"
/>
</FormGroup>
<FormHelperText>Be careful</FormHelperText>
</FormControl>
<FormControl
required
error={error}
component="fieldset"
sx={{ m: 3 }}
variant="standard"
>
<FormLabel component="legend">Pick two</FormLabel>
<FormGroup>
<FormControlLabel
control={
<Checkbox checked={gilad} onChange={handleChange} name="gilad" />
}
label="Gilad Gray"
/>
<FormControlLabel
control={
<Checkbox checked={jason} onChange={handleChange} name="jason" />
}
label="Jason Killian"
/>
<FormControlLabel
control={
<Checkbox checked={antoine} onChange={handleChange} name="antoine" />
}
label="Antoine Llorca"
/>
</FormGroup>
<FormHelperText>You can display an error</FormHelperText>
</FormControl>
</Box>
);
}
라벨 배치 (Label placement)
라벨의 배치를 변경할 수 있어요:
import Checkbox from '@mui/material/Checkbox';
import FormGroup from '@mui/material/FormGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
export default function FormControlLabelPosition() {
return (
<FormControl component="fieldset">
<FormLabel component="legend">Label placement</FormLabel>
<FormGroup aria-label="position" row>
<FormControlLabel
value="bottom"
control={<Checkbox />}
label="Bottom"
labelPlacement="bottom"
/>
<FormControlLabel
value="end"
control={<Checkbox />}
label="End"
labelPlacement="end"
/>
</FormGroup>
</FormControl>
);
}
커스터마이징 (Customization)
컴포넌트를 커스터마이징하는 예시예요. 자세한 내용은 오버라이드 문서 페이지에서 확인할 수 있어요.
import { styled } from '@mui/material/styles';
import Checkbox, { CheckboxProps } from '@mui/material/Checkbox';
const BpIcon = styled('span')(({ theme }) => ({
borderRadius: 3,
width: 16,
height: 16,
boxShadow: 'inset 0 0 0 1px rgba(16,22,26,.2), inset 0 -1px 0 rgba(16,22,26,.1)',
backgroundColor: '#f5f8fa',
backgroundImage: 'linear-gradient(180deg,hsla(0,0%,100%,.8),hsla(0,0%,100%,0))',
'.Mui-focusVisible &': {
outline: '2px auto rgba(19,124,189,.6)',
outlineOffset: 2,
},
'input:hover ~ &': {
backgroundColor: '#ebf1f5',
...theme.applyStyles('dark', {
backgroundColor: '#30404d',
}),
},
'input:disabled ~ &': {
boxShadow: 'none',
background: 'rgba(206,217,224,.5)',
...theme.applyStyles('dark', {
background: 'rgba(57,75,89,.5)',
}),
},
...theme.applyStyles('dark', {
boxShadow: '0 0 0 1px rgb(16 22 26 / 40%)',
backgroundColor: '#394b59',
backgroundImage: 'linear-gradient(180deg,hsla(0,0%,100%,.05),hsla(0,0%,100%,0))',
}),
}));
const BpCheckedIcon = styled(BpIcon)({
backgroundColor: '#137cbd',
backgroundImage: 'linear-gradient(180deg,hsla(0,0%,100%,.1),hsla(0,0%,100%,0))',
'&::before': {
display: 'block',
width: 16,
height: 16,
backgroundImage:
"url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath\" +
" fill-rule='evenodd' clip-rule='evenodd' d='M12 5c-.28 0-.53.11-.71.29L7 9.59l-2.29-2.3a1.003 " +
"1.003 0 00-1.42 1.42l3 3c.18.18.43.29.71.29s.53-.11.71-.29l5-5A1.003 1.003 0 0012 5z' fill='%23fff'/%3E%3C/svg%3E\")",
content: '""',
},
'input:hover ~ &': {
backgroundColor: '#106ba3',
},
});
// Inspired by blueprintjs
function BpCheckbox(props: CheckboxProps) {
return (
<Checkbox
sx={{ '&:hover': { bgcolor: 'transparent' } }}
disableRipple
color="default"
checkedIcon={<BpCheckedIcon />}
icon={<BpIcon />}
slotProps={{ input: { 'aria-label': 'Checkbox demo' } }}
{...props}
/>
);
}
export default function CustomizedCheckbox() {
return (
<div>
<BpCheckbox />
<BpCheckbox defaultChecked />
<BpCheckbox disabled />
</div>
);
}
🎨 영감을 찾고 있다면 MUI Treasury의 커스터마이징 예시를 확인해 보세요.
언제 사용할까 (When to use)
접근성 (Accessibility)
(WAI-ARIA: https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/)
- 모든 폼 컨트롤에는 라벨이 있어야 해요. 여기에는 라디오 버튼, 체크박스, 스위치가 포함됩니다. 대부분의 경우
<label>요소(FormControlLabel)를 사용해서 처리할 수 있어요. - 라벨을 사용할 수 없을 때는 input 컴포넌트에 직접 속성을 추가하는 것이 필요해요. 이 경우
slotProps.inputprop을 통해 추가 속성(예:aria-label,aria-labelledby,title)을 적용할 수 있어요.
<Checkbox
value="checkedA"
slotProps={{
input: { 'aria-label': 'Checkbox A' },
}}
/>
Checkbox API
데모 (Demos)
이 React 컴포넌트의 사용 예시와 자세한 내용은 컴포넌트 데모 페이지를 방문해 보세요:
Import
import Checkbox from '@mui/material/Checkbox';
// or
import { Checkbox } from '@mui/material';
Props
| 이름 (Name) | 타입 (Type) | 기본값 (Default) | 필수 (Required) | 설명 (Description) |
|---|---|---|---|---|
| checked | bool |
- | No | |
| checkedIcon | node |
<CheckBoxIcon /> |
No | |
| classes | object |
- | No | Override or extend the styles applied to the component. |
| color | 'default' | 'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning' | string |
'primary' |
No | |
| defaultChecked | bool |
- | No | |
| disabled | bool |
false |
No | |
| disableRipple | bool |
false |
No | |
| icon | node |
<CheckBoxOutlineBlankIcon /> |
No | |
| id | string |
- | No | |
| indeterminate | bool |
false |
No | |
| indeterminateIcon | node |
<IndeterminateCheckBoxIcon /> |
No | |
| onChange | function(event: React.ChangeEvent<HTMLInputElement>) => void |
- | No | |
| required | bool |
false |
No | |
| size | 'medium' | 'small' | string |
'medium' |
No | |
| slotProps | { input?: func | object, root?: func | object } |
{} |
No | |
| slots | { input?: elementType, root?: elementType } |
{} |
No | |
| sx | Array<func | object | bool> | func | object |
- | No | The system prop that allows defining system overrides as well as additional CSS styles. |
| value | any |
- | No |
참고 (Note):
ref는 루트 요소(HTMLSpanElement)로 전달됩니다.
제공된 다른 모든 props는 루트 요소(ButtonBase)로 전달됩니다.
상속 (Inheritance)
위에 명시적으로 문서화되진 않았지만, ButtonBase 컴포넌트의 props는 Checkbox에서도 사용할 수 있어요.
테마 기본 props (Theme default props)
MuiCheckbox를 사용해 테마로 이 컴포넌트의 기본 props를 변경할 수 있어요.
슬롯 (Slots)
| 이름 (Name) | 기본값 (Default) | 클래스 (Class) | 설명 (Description) |
|---|---|---|---|
| root | SwitchBase |
.MuiCheckbox-root |
The component that renders the root slot. |
| input | SwitchBase's input |
- | The component that renders the input slot. |
CSS
규칙 이름 (Rule name)
| 전역 클래스 (Global class) | 규칙 이름 (Rule name) | 설명 (Description) |
|---|---|---|
.Mui-checked |
- | State class applied to the root element if checked={true}. |
| - | colorPrimary | State class applied to the root element if color="primary". |
| - | colorSecondary | State class applied to the root element if color="secondary". |
.Mui-disabled |
- | State class applied to the root element if disabled={true}. |
| - | indeterminate | State class applied to the root element if indeterminate={true}. |
| - | sizeMedium | State class applied to the root element if size="medium". |
| - | sizeSmall | State class applied to the root element if size="small". |
소스 코드 (Source code)
이 페이지에서 필요한 정보를 찾지 못했다면, 컴포넌트의 구현을 살펴보면서 더 자세한 내용을 확인해 보세요.
FormControl API
데모 (Demos)
이 React 컴포넌트의 사용 예시와 자세한 내용은 컴포넌트 데모 페이지를 방문해 보세요:
Import
import FormControl from '@mui/material/FormControl';
// or
import { FormControl } from '@mui/material';
Props
| 이름 (Name) | 타입 (Type) | 기본값 (Default) | 필수 (Required) | 설명 (Description) |
|---|---|---|---|---|
| children | node |
- | No | |
| classes | object |
- | No | Override or extend the styles applied to the component. |
| color | 'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning' | string |
'primary' |
No | |
| component | elementType |
- | No | |
| disabled | bool |
false |
No | |
| error | bool |
false |
No | |
| focused | bool |
- | No | |
| fullWidth | bool |
false |
No | |
| hiddenLabel | bool |
false |
No | |
| margin | 'dense' | 'none' | 'normal' |
'none' |
No | |
| required | bool |
false |
No | |
| size | 'medium' | 'small' | string |
'medium' |
No | |
| sx | Array<func | object | bool> | func | object |
- | No | The system prop that allows defining system overrides as well as additional CSS styles. |
| variant | 'filled' | 'outlined' | 'standard' |
'outlined' |
No |
참고 (Note):
ref는 루트 요소(HTMLDivElement)로 전달됩니다.
제공된 다른 모든 props는 루트 요소(네이티브 요소)로 전달됩니다.
테마 기본 props (Theme default props)
MuiFormControl를 사용해 테마로 이 컴포넌트의 기본 props를 변경할 수 있어요.
CSS
규칙 이름 (Rule name)
| 전역 클래스 (Global class) | 규칙 이름 (Rule name) | 설명 (Description) |
|---|---|---|
| - | fullWidth | Styles applied to the root element if fullWidth={true}. |
| - | marginDense | Styles applied to the root element if margin="dense". |
| - | marginNormal | Styles applied to the root element if margin="normal". |
| - | root | Styles applied to the root element. |
소스 코드 (Source code)
이 페이지에서 필요한 정보를 찾지 못했다면, 컴포넌트의 구현을 살펴보면서 더 자세한 내용을 확인해 보세요.
FormControlLabel API
데모 (Demos)
이 React 컴포넌트의 사용 예시와 자세한 내용은 컴포넌트 데모 페이지를 방문해 보세요:
Import
import FormControlLabel from '@mui/material/FormControlLabel';
// or
import { FormControlLabel } from '@mui/material';
Props
| 이름 (Name) | 타입 (Type) | 기본값 (Default) | 필수 (Required) | 설명 (Description) |
|---|---|---|---|---|
| control | element |
- | Yes | |
| checked | bool |
- | No | |
| classes | object |
- | No | Override or extend the styles applied to the component. |
| disabled | bool |
- | No | |
| disableTypography | bool |
- | No | |
| inputRef | ref |
- | No | |
| label | node |
- | No | |
| labelPlacement | 'bottom' | 'end' | 'start' | 'top' |
'end' |
No | |
| onChange | function(event: React.SyntheticEvent) => void |
- | No | |
| required | bool |
- | No | |
| slotProps | { typography?: func | object } |
{} |
No | |
| slots | { typography?: elementType } |
{} |
No | |
| sx | Array<func | object | bool> | func | object |
- | No | The system prop that allows defining system overrides as well as additional CSS styles. |
| value | any |
- | No |
참고 (Note):
ref는 루트 요소(HTMLLabelElement)로 전달됩니다.
제공된 다른 모든 props는 루트 요소(네이티브 요소)로 전달됩니다.
테마 기본 props (Theme default props)
MuiFormControlLabel를 사용해 테마로 이 컴포넌트의 기본 props를 변경할 수 있어요.
슬롯 (Slots)
| 이름 (Name) | 기본값 (Default) | 클래스 (Class) | 설명 (Description) |
|---|---|---|---|
| typography | Typography |
- | The component that renders the label. |
This is unused if disableTypography is true. |
CSS
규칙 이름 (Rule name)
| 전역 클래스 (Global class) | 규칙 이름 (Rule name) | 설명 (Description) |
|---|---|---|
| - | asterisk | Styles applied to the asterisk element. |
.Mui-disabled |
- | State class applied to the root element if disabled={true}. |
.Mui-error |
- | State class applied to the root element if error={true}. |
| - | label | Styles applied to the label's Typography component. |
| - | labelPlacementBottom | Styles applied to the root element if labelPlacement="bottom". |
| - | labelPlacementEnd | Styles applied to the root element if labelPlacement="end". |
| - | labelPlacementStart | Styles applied to the root element if labelPlacement="start". |
| - | labelPlacementTop | Styles applied to the root element if labelPlacement="top". |
.Mui-required |
- | State class applied to the root element if required={true}. |
| - | root | Styles applied to the root element. |
소스 코드 (Source code)
이 페이지에서 필요한 정보를 찾지 못했다면, 컴포넌트의 구현을 살펴보면서 더 자세한 내용을 확인해 보세요.
FormGroup API
데모 (Demos)
이 React 컴포넌트의 사용 예시와 자세한 내용은 컴포넌트 데모 페이지를 방문해 보세요:
Import
import FormGroup from '@mui/material/FormGroup';
// or
import { FormGroup } from '@mui/material';
Props
| 이름 (Name) | 타입 (Type) | 기본값 (Default) | 필수 (Required) | 설명 (Description) |
|---|---|---|---|---|
| children | node |
- | No | |
| classes | object |
- | No | Override or extend the styles applied to the component. |
| row | bool |
false |
No | |
| sx | Array<func | object | bool> | func | object |
- | No | The system prop that allows defining system overrides as well as additional CSS styles. |
참고 (Note):
ref는 루트 요소(HTMLDivElement)로 전달됩니다.
제공된 다른 모든 props는 루트 요소(네이티브 요소)로 전달됩니다.
테마 기본 props (Theme default props)
MuiFormGroup를 사용해 테마로 이 컴포넌트의 기본 props를 변경할 수 있어요.
CSS
규칙 이름 (Rule name)
| 전역 클래스 (Global class) | 규칙 이름 (Rule name) | 설명 (Description) |
|---|---|---|
.Mui-error |
- | State class applied to the root element if error={true}. |
| - | root | Styles applied to the root element. |
| - | row | Styles applied to the root element if row={true}. |
소스 코드 (Source code)
이 페이지에서 필요한 정보를 찾지 못했다면, 컴포넌트의 구현을 살펴보면서 더 자세한 내용을 확인해 보세요.
FormLabel API
데모 (Demos)
이 React 컴포넌트의 사용 예시와 자세한 내용은 컴포넌트 데모 페이지를 방문해 보세요:
Import
import FormLabel from '@mui/material/FormLabel';
// or
import { FormLabel } from '@mui/material';
Props
| 이름 (Name) | 타입 (Type) | 기본값 (Default) | 필수 (Required) | 설명 (Description) |
|---|---|---|---|---|
| children | node |
- | No | |
| classes | object |
- | No | Override or extend the styles applied to the component. |
| color | 'error' | 'info' | 'primary' | 'secondary' | 'success' | 'warning' | string |
- | No | |
| component | elementType |
- | No | |
| disabled | bool |
- | No | |
| error | bool |
- | No | |
| filled | bool |
- | No | |
| focused | bool |
- | No | |
| required | bool |
- | No | |
| sx | Array<func | object | bool> | func | object |
- | No | The system prop that allows defining system overrides as well as additional CSS styles. |
참고 (Note):
ref는 루트 요소(HTMLLabelElement)로 전달됩니다.
제공된 다른 모든 props는 루트 요소(네이티브 요소)로 전달됩니다.
테마 기본 props (Theme default props)
MuiFormLabel를 사용해 테마로 이 컴포넌트의 기본 props를 변경할 수 있어요.
CSS
규칙 이름 (Rule name)
| 전역 클래스 (Global class) | 규칙 이름 (Rule name) | 설명 (Description) |
|---|---|---|
| - | asterisk | Styles applied to the asterisk element. |
| - | colorSecondary | Styles applied to the root element if the color is secondary. |
.Mui-disabled |
- | State class applied to the root element if disabled={true}. |
.Mui-error |
- | State class applied to the root element if error={true}. |
| - | filled | State class applied to the root element if filled={true}. |
.Mui-focused |
- | State class applied to the root element if focused={true}. |
.Mui-required |
- | State class applied to the root element if required={true}. |
| - | root | Styles applied to the root element. |
소스 코드 (Source code)
이 페이지에서 필요한 정보를 찾지 못했다면, 컴포넌트의 구현을 살펴보면서 더 자세한 내용을 확인해 보세요.