본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

라디오 그룹 (Radio Group)

원문 보기 위키 갱신

SlRadioGroup은 여러 개의 라디오(radio) 또는 라디오 버튼(radio button)을 하나의 폼 컨트롤처럼 동작하도록 묶어주는 요소예요. 그룹 안에서 하나의 옵션만 선택할 수 있게 해줍니다.

출처: 문서

본문

<sl-radio-group label="Select an option" name="a" value="1">
  <sl-radio value="1">Option 1</sl-radio>
  <sl-radio value="2">Option 2</sl-radio>
  <sl-radio value="3">Option 3</sl-radio>
</sl-radio-group>

React에서는 이렇게 사용할 수 있어요.

import SlRadio from '@shoelace-style/shoelace/dist/react/radio';
import SlRadioGroup from '@shoelace-style/shoelace/dist/react/radio-group';
const App = () => (
  <SlRadioGroup label="Select an option" name="a" value="1">
    <SlRadio value="1">Option 1</SlRadio>
    <SlRadio value="2">Option 2</SlRadio>
    <SlRadio value="3">Option 3</SlRadio>
  </SlRadioGroup>
);

예시 (Examples)

도움말 텍스트 (Help Text)

help-text 속성을 사용하면 라디오 그룹에 설명용 도움말 텍스트를 추가할 수 있어요. HTML이 포함된 도움말이 필요하다면 help-text 슬롯을 대신 사용하세요.

<sl-radio-group label="Select an option" help-text="Choose the most appropriate option." name="a" value="1">
  <sl-radio value="1">Option 1</sl-radio>
  <sl-radio value="2">Option 2</sl-radio>
  <sl-radio value="3">Option 3</sl-radio>
</sl-radio-group>
import SlRadio from '@shoelace-style/shoelace/dist/react/radio';
import SlRadioGroup from '@shoelace-style/shoelace/dist/react/radio-group';
const App = () => (
  <SlRadioGroup label="Select an option" help-text="Choose the most appropriate option." name="a" value="1">
    <SlRadio value="1">Option 1</SlRadio>
    <SlRadio value="2">Option 2</SlRadio>
    <SlRadio value="3">Option 3</SlRadio>
  </SlRadioGroup>
);

라디오 버튼 (Radio Buttons)

Radio button은 라디오 컨트롤을 표시하는 또 다른 방법을 제공해요. 이 경우 내부의 버튼 그룹이 버튼들을 하나의 응집된 컨트롤로 묶어 주는 역할을 합니다.

<sl-radio-group label="Select an option" help-text="Select an option that makes you proud." name="a" value="1">
  <sl-radio-button value="1">Option 1</sl-radio-button>
  <sl-radio-button value="2">Option 2</sl-radio-button>
  <sl-radio-button value="3">Option 3</sl-radio-button>
</sl-radio-group>
import SlRadioButton from '@shoelace-style/shoelace/dist/react/radio-button';
import SlRadioGroup from '@shoelace-style/shoelace/dist/react/radio-group';
const App = () => (
  <SlRadioGroup label="Select an option" name="a" value="1">
    <SlRadioButton value="1">Option 1</SlRadioButton>
    <SlRadioButton value="2">Option 2</SlRadioButton>
    <SlRadioButton value="3">Option 3</SlRadioButton>
  </SlRadioGroup>
);

옵션 비활성화 (Disabling Options)

라디오 그룹 안에 있는 각 옵션에 disabled 속성을 추가하면 라디오와 radio button을 개별적으로 비활성화할 수 있어요.

<sl-radio-group label="Select an option" name="a" value="1">
  <sl-radio value="1">Option 1</sl-radio>
  <sl-radio value="2" disabled>Option 2</sl-radio>
  <sl-radio value="3">Option 3</sl-radio>
</sl-radio-group>
import SlRadio from '@shoelace-style/shoelace/dist/react/radio';
import SlRadioGroup from '@shoelace-style/shoelace/dist/react/radio-group';
const App = () => (
  <SlRadioGroup label="Select an option" name="a" value="1">
    <SlRadio value="1">Option 1</SlRadio>
    <SlRadio value="2" disabled>
      Option 2
    </SlRadio>
    <SlRadio value="3">Option 3</SlRadio>
  </SlRadioGroup>
);

크기 옵션 (Sizing Options)

Radio와 Radio Button의 크기는 Radio Group의 size 속성에 따라 결정돼요.

<sl-radio-group label="Select an option" size="medium" value="medium" class="radio-group-size">
  <sl-radio value="small">Small</sl-radio>
  <sl-radio value="medium">Medium</sl-radio>
  <sl-radio value="large">Large</sl-radio>
</sl-radio-group>
<script>
  const radioGroup = document.querySelector('.radio-group-size');
  radioGroup.addEventListener('sl-change', () => {
    radioGroup.size = radioGroup.value;
  });
</script>
import { useState } from 'react';
import SlRadio from '@shoelace-style/shoelace/dist/react/radio';
import SlRadioGroup from '@shoelace-style/shoelace/dist/react/radio-group';
const App = () => {
  const [size, setSize] = useState('medium');
  return (
    <>
      <SlRadioGroup
        label="Select an option"
        size={size}
        value={size}
        class="radio-group-size"
        onSlChange={event => setSize(event.target.value)}
      >
        <SlRadio value="small">Small</SlRadio>
        <SlRadio value="medium">Medium</SlRadio>
        <SlRadio value="large">Large</SlRadio>
      </SlRadioGroup>
    </>
  );
};

Radio와 Radio Button에도 각각 size 속성이 있어요. 특정 구성에서 유용할 수 있지만, Radio Group 안에서 사용하면 이 값은 무시됩니다.

유효성 검사 (Validation)

required 속성을 설정하면 옵션 선택을 필수로 만들 수 있어요. 값을 선택하지 않으면 폼 제출을 막고 오류 메시지를 표시해 줍니다.

<form class="validation">
  <sl-radio-group label="Select an option" name="a" required>
    <sl-radio value="1">Option 1</sl-radio>
    <sl-radio value="2">Option 2</sl-radio>
    <sl-radio value="3">Option 3</sl-radio>
  </sl-radio-group>
  <br />
  <sl-button type="submit" variant="primary">Submit</sl-button>
</form>
<script>
  const form = document.querySelector('.validation');
  // Handle form submit
  form.addEventListener('submit', event => {
    event.preventDefault();
    alert('All fields are valid!');
  });
</script>
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlIcon from '@shoelace-style/shoelace/dist/react/icon';
import SlRadio from '@shoelace-style/shoelace/dist/react/radio';
import SlRadioGroup from '@shoelace-style/shoelace/dist/react/radio-group';
const App = () => {
  function handleSubmit(event) {
    event.preventDefault();
    alert('All fields are valid!');
  }
  return (
    <form class="custom-validity" onSubmit={handleSubmit}>
      <SlRadioGroup label="Select an option" name="a" required onSlChange={handleChange}>
        <SlRadio value="1">
          Option 1
        </SlRadio>
        <SlRadiovalue="2">
          Option 2
        </SlRadio>
        <SlRadio value="3">
          Option 3
        </SlRadio>
      </SlRadioGroup>
      <br />
      <SlButton type="submit" variant="primary">
        Submit
      </SlButton>
    </form>
  );
};

커스텀 유효성 (Custom Validity)

setCustomValidity() 메서드로 커스텀 유효성 검사 메시지를 설정할 수 있어요. 이렇게 하면 폼 제출을 막고 브라우저가 직접 제공한 오류 메시지를 표시하게 됩니다. 오류를 지우려면 빈 문자열을 인자로 넘겨 호출하면 돼요.

<form class="custom-validity">
  <sl-radio-group label="Select an option" name="a" value="1">
    <sl-radio value="1">Not me</sl-radio>
    <sl-radio value="2">Me neither</sl-radio>
    <sl-radio value="3">Choose me</sl-radio>
  </sl-radio-group>
  <br />
  <sl-button type="submit" variant="primary">Submit</sl-button>
</form>
<script>
  const form = document.querySelector('.custom-validity');
  const radioGroup = form.querySelector('sl-radio-group');
  const errorMessage = 'You must choose the last option';
  // Set initial validity as soon as the element is defined
  customElements.whenDefined('sl-radio').then(() => {
    radioGroup.setCustomValidity(errorMessage);
  });
  // Update validity when a selection is made
  form.addEventListener('sl-change', () => {
    const isValid = radioGroup.value === '3';
    radioGroup.setCustomValidity(isValid ? '' : errorMessage);
  });
  // Handle form 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 SlIcon from '@shoelace-style/shoelace/dist/react/icon';
import SlRadio from '@shoelace-style/shoelace/dist/react/radio';
import SlRadioGroup from '@shoelace-style/shoelace/dist/react/radio-group';
const App = () => {
  const radioGroup = useRef(null);
  const errorMessage = 'You must choose this option';
  function handleChange() {
    radioGroup.current.setCustomValidity(radioGroup.current.value === '3' ? '' : errorMessage);
  }
  function handleSubmit(event) {
    event.preventDefault();
    alert('All fields are valid!');
  }
  useEffect(() => {
    radio.current.setCustomValidity(errorMessage);
  }, []);
  return (
    <form class="custom-validity" onSubmit={handleSubmit}>
      <SlRadioGroup ref={radioGroup} label="Select an option" name="a" value="1" onSlChange={handleChange}>
        <SlRadio value="1">Not me</SlRadio>
        <SlRadio value="2">Me neither</SlRadio>
        <SlRadio value="3">Choose me</SlRadio>
      </SlRadioGroup>
      <br />
      <SlButton type="submit" variant="primary">
        Submit
      </SlButton>
    </form>
  );
};

불러오기 (Importing)

autoloader나 전통적인 loader를 사용 중이라면 이 부분은 무시해도 돼요. 그게 아니라면 아래 스니펫 중 원하는 방식으로 이 컴포넌트만 골라서 불러올 수 있어요.

Script 태그로 CDN에서 이 컴포넌트를 불러오려면:

<script type="module" src="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/components/radio-group/radio-group.js"></script>

JavaScript import 구문으로 CDN에서 불러오려면:

import 'https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/components/radio-group/radio-group.js';

번들러(bundler)를 사용해 불러오려면:

import '@shoelace-style/shoelace/dist/components/radio-group/radio-group.js';

React 컴포넌트로 불러오려면:

import SlRadioGroup from '@shoelace-style/shoelace/dist/react/radio-group';

슬롯 (Slots)

Name Description
(default) The default slot where or elements are placed.
label The radio group’s label. Required for proper accessibility. Alternatively, you can use the label attribute.
help-text Text that describes how to use the radio group. Alternatively, you can use the help-text attribute.

슬롯 사용법에 대해 더 알아보기.

속성 (Properties)

Name Description Reflects Type Default
label The radio group’s label. Required for proper accessibility. If you need to display HTML, use the label slot instead. string ''
helpText help-text The radio groups’s help text. If you need to display HTML, use the help-text slot instead. string ''
name The name of the radio group, submitted as a name/value pair with form data. string 'option'
value The current value of the radio group, submitted as a name/value pair with form data. string ''
size The radio group’s size. This size will be applied to all child radios and radio buttons. 'small' | 'medium' | 'large' 'medium'
form By default, form controls are associated with the nearest containing `` 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 Ensures a child radio is checked before allowing the containing form to submit. boolean false
validity Gets the validity state object - -
validationMessage Gets the validation message - -
updateComplete A read-only promise that resolves when the component has finished updating.

속성(attribute)과 프로퍼티(property)에 대해 더 알아보기.

이벤트 (Events)

Name React Event Description Event Detail
sl-change onSlChange Emitted when the radio group’s selected value changes. -
sl-input onSlInput Emitted when the radio group receives user input. -
sl-invalid onSlInvalid Emitted when the form control has been checked for validity and its constraints aren’t satisfied. -

이벤트에 대해 더 알아보기.

메서드 (Methods)

Name Description Arguments
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. Pass an empty string to restore validity. message:
focus() Sets focus on the radio-group. options: FocusOptions

메서드에 대해 더 알아보기.

파트 (Parts)

Name Description
form-control The form control that wraps the label, input, and help text.
form-control-label The label’s wrapper.
form-control-input The input’s wrapper.
form-control-help-text The help text’s wrapper.
button-group The button group that wraps radio buttons.
button-group__base The button group’s base part.

CSS 파트 커스터마이징에 대해 더 알아보기.

의존성 (Dependencies)

이 컴포넌트는 다음 의존성을 자동으로 불러옵니다.

  • ``

더 알아보기 (Learn more)