Checkbox
Shoelace의 Checkbox 컴포넌트(sl-checkbox)는 사용자가 옵션을 켜고(on) 끌(off) 수 있게 해주는 체크박스 요소예요. checked, indeterminate, disabled 상태를 지원하고, 폼 제출 및 클라이언트 측 검증(validation)에도 사용할 수 있답니다.
출처: 문서
본문
Checkbox는 사용자가 옵션을 켜거나 끌 수 있게 해줘요.
<sl-checkbox>Checkbox</sl-checkbox>
import SlCheckbox from '@shoelace-style/shoelace/dist/react/checkbox';
const App = () => <SlCheckbox>Checkbox</SlCheckbox>;
이 컴포넌트는 표준 <form> 요소와 함께 동작해요. 폼 제출과 클라이언트 측 검증에 대해 더 알아보려면 form controls 섹션을 참고하세요.
Examples
Checked
checked 속성(attribute)을 사용하면 체크박스를 활성화할 수 있어요.
<sl-checkbox checked>Checked</sl-checkbox>
import SlCheckbox from '@shoelace-style/shoelace/dist/react/checkbox';
const App = () => <SlCheckbox checked>Checked</SlCheckbox>;
Indeterminate
indeterminate 속성(attribute)을 사용하면 체크박스를 불확정(indeterminate) 상태로 만들 수 있어요.
<sl-checkbox indeterminate>Indeterminate</sl-checkbox>
import SlCheckbox from '@shoelace-style/shoelace/dist/react/checkbox';
const App = () => <SlCheckbox indeterminate>Indeterminate</SlCheckbox>;
Disabled
disabled 속성(attribute)을 사용하면 체크박스를 비활성화할 수 있어요.
<sl-checkbox disabled>Disabled</sl-checkbox>
import SlCheckbox from '@shoelace-style/shoelace/dist/react/checkbox';
const App = () => <SlCheckbox disabled>Disabled</SlCheckbox>;
Sizes
size 속성(attribute)을 사용해 체크박스 크기를 바꿀 수 있어요.
<sl-checkbox size="small">Small</sl-checkbox>
<br />
<sl-checkbox size="medium">Medium</sl-checkbox>
<br />
<sl-checkbox size="large">Large</sl-checkbox>
import SlCheckbox from '@shoelace-style/shoelace/dist/react/checkbox';
const App = () => (
<>
<SlCheckbox size="small">Small</SlCheckbox>
<br />
<SlCheckbox size="medium">Medium</SlCheckbox>
<br />
<SlCheckbox size="large">Large</SlCheckbox>
</>
);
Help Text
help-text 속성(attribute)으로 체크박스에 설명적인 도움말 텍스트를 추가할 수 있어요. HTML이 포함된 도움말 텍스트에는 help-text 슬롯을 사용하세요.
<sl-checkbox help-text="What should the user know about the checkbox?">Label</sl-checkbox>
import SlCheckbox from '@shoelace-style/shoelace/dist/react/checkbox';
const App = () => <SlCheckbox help-text="What should the user know about the switch?">Label</SlCheckbox>;
Custom Validity
setCustomValidity() 메서드를 사용하면 사용자 지정 검증 메시지를 설정할 수 있어요. 이렇게 하면 폼 제출을 막고 브라우저가 제공한 오류 메시지를 표시하게 돼요. 오류를 지우려면 빈 문자열로 이 함수를 호출하면 됩니다.
<form class="custom-validity">
<sl-checkbox>Check me</sl-checkbox>
<br />
<sl-button type="submit" variant="primary" style="margin-top: 1rem;">Submit</sl-button>
</form>
<script>
const form = document.querySelector('.custom-validity');
const checkbox = form.querySelector('sl-checkbox');
const errorMessage = `Don't forget to check me!`;
// Set initial validity as soon as the element is defined
customElements.whenDefined('sl-checkbox').then(async () => {
await checkbox.updateComplete;
checkbox.setCustomValidity(errorMessage);
});
// Update validity on change
checkbox.addEventListener('sl-change', () => {
checkbox.setCustomValidity(checkbox.checked ? '' : errorMessage);
});
// Handle submit
form.addEventListener('submit', event => {
event.preventDefault();
alert('All fields are valid!');
});
</script>
import { useEffect, useRef } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlCheckbox from '@shoelace-style/shoelace/dist/react/checkbox';
const App = () => {
const checkbox = useRef(null);
const errorMessage = `Don't forget to check me!`;
function handleChange() {
checkbox.current.setCustomValidity(checkbox.current.checked ? '' : errorMessage);
}
function handleSubmit(event) {
event.preventDefault();
alert('All fields are valid!');
}
useEffect(() => {
checkbox.current.setCustomValidity(errorMessage);
}, []);
return (
<form class="custom-validity" onSubmit={handleSubmit}>
<SlCheckbox ref={checkbox} onSlChange={handleChange}>
Check me
</SlCheckbox>
<br />
<SlButton type="submit" variant="primary" style={{ marginTop: '1rem' }}>
Submit
</SlButton>
</form>
);
};
Importing
autoloader나 전통적인 loader를 사용하고 있다면 이 부분은 무시해도 돼요. 그 외의 경우 아래 스니펫 중 하나를 골라 이 컴포넌트만 골라(cherry pick) 가져올 수 있답니다.
Script / Import / Bundler / React
CDN에서 script 태그로 이 컴포넌트를 가져오려면:
<script type="module" src="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/components/checkbox/checkbox.js"></script>
CDN에서 JavaScript import로 이 컴포넌트를 가져오려면:
import 'https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/components/checkbox/checkbox.js';
bundler를 사용해 이 컴포넌트를 가져오려면:
import '@shoelace-style/shoelace/dist/components/checkbox/checkbox.js';
이 컴포넌트를 React 컴포넌트로 가져오려면:
import SlCheckbox from '@shoelace-style/shoelace/dist/react/checkbox';
Slots
| Name | Description |
|---|---|
| (default) | The checkbox’s label. |
help-text |
Text that describes how to use the checkbox. Alternatively, you can use the help-text attribute. |
슬롯(slots) 사용에 대해 더 알아보기.
Properties
| Name | Description | Reflects | Type | Default |
|---|---|---|---|---|
name |
The name of the checkbox, submitted as a name/value pair with form data. | string |
'' |
|
value |
The current value of the checkbox, submitted as a name/value pair with form data. | string |
- | |
size |
The checkbox’s size. | 'small' | 'medium' | 'large' |
'medium' |
|
disabled |
Disables the checkbox. | boolean |
false |
|
checked |
Draws the checkbox in a checked state. | boolean |
false |
|
indeterminate |
Draws the checkbox in an indeterminate state. This is usually applied to checkboxes that represents a “select all/none” behavior when associated checkboxes have a mix of checked and unchecked states. | boolean |
false |
|
defaultChecked |
The default value of the form control. Primarily used for resetting the form control. | boolean |
false |
|
form |
By default, form controls are associated with the nearest containing <form> element. This attribute allows you to place the form control outside of a form and associate it with the form that has this id. The form must be in the same document or shadow root for this to work. |
string |
'' |
|
required |
Makes the checkbox a required field. | boolean |
false |
|
helpText / help-text |
The checkbox’s help text. If you need to display HTML, use the help-text slot instead. |
string |
'' |
|
validity |
Gets the validity state object | - | - | |
validationMessage |
Gets the validation message | - | - | |
updateComplete |
A read-only promise that resolves when the component has finished updating. |
속성과 프로퍼티(attributes and properties)에 대해 더 알아보기.
Events
| Name | React Event | Description | Event Detail |
|---|---|---|---|
sl-blur |
onSlBlur |
Emitted when the checkbox loses focus. | - |
sl-change |
onSlChange |
Emitted when the checked state changes. | - |
sl-focus |
onSlFocus |
Emitted when the checkbox gains focus. | - |
sl-input |
onSlInput |
Emitted when the checkbox receives input. | - |
sl-invalid |
onSlInvalid |
Emitted when the form control has been checked for validity and its constraints aren’t satisfied. | - |
이벤트(events)에 대해 더 알아보기.
Methods
| Name | Description | Arguments |
|---|---|---|
click() |
Simulates a click on the checkbox. | - |
focus() |
Sets focus on the checkbox. | options: FocusOptions |
blur() |
Removes focus from the checkbox. | - |
checkValidity() |
Checks for validity but does not show a validation message. Returns true when valid and false when invalid. |
- |
getForm() |
Gets the associated form, if one exists. | - |
reportValidity() |
Checks for validity and shows the browser’s validation message if the control is invalid. | - |
setCustomValidity() |
Sets a custom validation message. The value provided will be shown to the user when the form is submitted. To clear the custom validation message, call this method with an empty string. | message: string |
메서드(methods)에 대해 더 알아보기.
Parts
| Name | Description |
|---|---|
base |
The component’s base wrapper. |
control |
The square container that wraps the checkbox’s checked state. |
control--checked |
Matches the control part when the checkbox is checked. |
control--indeterminate |
Matches the control part when the checkbox is indeterminate. |
checked-icon |
The checked icon, an sl-icon element. |
indeterminate-icon |
The indeterminate icon, an sl-icon element. |
label |
The container that wraps the checkbox’s label. |
form-control-help-text |
The help text’s wrapper. |
CSS 파트(parts) 커스터마이징에 대해 더 알아보기.
Dependencies
이 컴포넌트는 다음 의존성들을 자동으로 가져와요.
sl-icon
더 알아보기 (Learn more)
- Shoelace 시작하기(getting started) — 컴포넌트 설치와 로딩 방법
- Shoelace Form Controls — 폼 제출과 클라이언트 측 검증 방법
- Shoelace Switch 컴포넌트 — 체크박스와 비슷한 켜기/끄기 토글 컴포넌트