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

Chat - 제안(Suggestions)

원문 보기 위키 갱신

사용자가 대화를 시작하거나 다음 프롬프트를 고르도록 도와주는 프롬프트 제안을 표시할 수 있어요.

출처: MUI X documentation

본문

인터랙티브 플레이그라운드

제안은 클릭 가능한 프롬프트예요. 대화가 비어 있는 동안에는 메시지 영역 가운데에 정렬된 알약(pill)으로 나타나고, 메시지가 생기면 ChatBox는 그것들을 컴포저 위의 가로 스크롤 행으로 유지해요. 제안을 클릭하면 컴포저에 제안 텍스트가 미리 채워져 사용자가 대화의 시작점을 갖게 돼요.

제안 목록을 편집하고 레이아웃 옵션을 토글해 보세요:

import * as React from 'react';
import Box from '@mui/material/Box';
import { ChatSuggestions } from '@mui/x-chat';
import { PlaygroundCard } from 'docs/src/modules/components/chat-playground/PlaygroundCard';
import { ScopedChat } from 'docs/src/modules/components/chat-playground/sharedProviders';
import {
  directoryConversations,
  emptyConversation,
  groupThreadMessages,
} from 'docs/src/modules/components/chat-playground/sharedFixtures';
import {
  DividerLabel,
  NumberControl,
  SwitchControl,
  TextControl,
} from 'docs/src/modules/components/chat-playground/controls';
import {
  useCustomizations,
  type CustomizationDef,
} from 'docs/src/modules/components/chat-playground/useCustomizations';

const POOL = [
  'Show me the default ChatComposer',
  'How do I style ChatMessage bubbles?',
  'Render code blocks with syntax highlighting',
  'Wire up RAG sources',
  'Toggle dark mode in MUI X Chat',
  'Customise the conversation list row',
  'Disable attachments on the composer',
];

type ClassKey = 'root' | 'item';

const CLASS_DEFS: ReadonlyArray<CustomizationDef<ClassKey>> = [
  { name: 'root', description: 'The root container of the suggestions row.' },
  {
    name: 'item',
    selector: '.MuiChatSuggestions-item',
    description: 'Each suggestion pill.',
  },
];

export default function ChatSuggestionsPlayground() {
  const [count, setCount] = React.useState(4);
  const [autoSubmit, setAutoSubmit] = React.useState(false);
  const [alwaysVisible, setAlwaysVisible] = React.useState(false);
  const [hasMessages, setHasMessages] = React.useState(false);
  const [first, setFirst] = React.useState(POOL[0]);
  const classesCustomizations = useCustomizations<ClassKey>(CLASS_DEFS);

  const suggestions = React.useMemo(() => {
    const list = [first, ...POOL.slice(1)].slice(0, count);
    return list;
  }, [count, first]);

  const rootSx = classesCustomizations.toClassesSx();

  return (
    <PlaygroundCard
      title="ChatSuggestions"
      description="Pill-style prompts for the active thread. By default they only render while the thread is empty; alwaysVisible keeps them available as a next-prompt row."
      previewMinHeight={180}
      classCustomizations={classesCustomizations.customizations}
      onClassesReset={classesCustomizations.reset}
      controls={
        <React.Fragment>
          <DividerLabel>props</DividerLabel>
          <SwitchControl
            label="autoSubmit"
            checked={autoSubmit}
            onChange={setAutoSubmit}
            helperText="Submit on click instead of populating the input."
          />
          <SwitchControl
            label="alwaysVisible"
            checked={alwaysVisible}
            onChange={setAlwaysVisible}
            helperText="Render even when the active thread has messages."
          />
          <DividerLabel>preview state</DividerLabel>
          <SwitchControl
            label="thread has messages"
            checked={hasMessages}
            onChange={setHasMessages}
            helperText="Seed the preview thread with messages. With alwaysVisible off, the suggestions render nothing."
          />
          <DividerLabel>suggestions data</DividerLabel>
          <NumberControl
            label="suggestion count"
            value={count}
            min={1}
            max={POOL.length}
            onChange={setCount}
          />
          <TextControl label="first suggestion" value={first} onChange={setFirst} />
        </React.Fragment>
      }
      preview={
        <ScopedChat
          conversations={
            hasMessages ? [directoryConversations[0]] : [emptyConversation]
          }
          messages={hasMessages ? groupThreadMessages : undefined}
          activeConversationId={hasMessages ? 'styling' : emptyConversation.id}
        >
          <Box sx={{ width: '100%' }}>
            <ChatSuggestions
              suggestions={suggestions}
              autoSubmit={autoSubmit}
              alwaysVisible={alwaysVisible}
              sx={rootSx}
            />
          </Box>
        </ScopedChat>
      }
    />
  );
}

제안 구현하기

ChatBox의 suggestions prop에 문자열 배열을 전달하세요:

<ChatBox
  adapter={adapter}
  suggestions={[
    'What can you help me with?',
    'Summarize my latest report',
    'Write a follow-up email',
  ]}
/>

대화가 비어 있는 동안 제안은 메시지 영역에 가운데 정렬된 알약으로 렌더링돼요. 첫 번째 메시지가 나타나면 ChatBox는 제안을 컴포저 위의 행으로 옮깁니다. 활성 대화에서의 제안을 참고하세요.

제안 라벨 커스터마이징

더 많은 제어가 필요하면 일반 문자열 대신 ChatSuggestion 객체를 전달하세요. 이렇게 하면 컴포저에 미리 채워지는 값과 다른 표시 라벨을 설정할 수 있어요:

'use client';
import * as React from 'react';
import { ChatBox } from '@mui/x-chat';
import { createEchoAdapter } from 'docs/data/chat/core/examples/shared/demoUtils';
import { minimalConversation } from 'docs/data/chat/core/examples/shared/demoData';

const adapter = createEchoAdapter();

export default function SuggestionsWithLabels() {
  return (
    <ChatBox
      adapter={adapter}
      initialActiveConversationId={minimalConversation.id}
      // Seed only the conversation (no messages) so the empty-state suggestions show.
      initialConversations={[minimalConversation]}
      suggestions={[
        {
          value:
            'Help me write a professional email to my manager about taking PTO next week',
          label: 'Write an email',
        },
        {
          value: 'Summarize the key points from my Q4 performance review',
          label: 'Summarize a document',
        },
        {
          value: 'What are the best practices for React state management in 2026?',
          label: 'Ask a question',
        },
      ]}
      sx={{
        height: 500,
        border: '1px solid',
        borderColor: 'divider',
        borderRadius: 1,
      }}
    />
  );
}

제안 객체 구조

속성 타입 설명
value string 클릭했을 때 컴포저에 미리 채울 값.
label string 선택적 표시 라벨. 생략하면 value로 대체됩니다.

같은 배열에서 문자열과 객체를 섞을 수 있어요. 문자열은 내부적으로 { value: string }으로 정규화됩니다.

제안 자동 제출

기본적으로 제안을 클릭하면 컴포저에 미리 채워져서 사용자가 보내기 전에 검토하거나 편집할 수 있어요. suggestionsAutoSubmit을 설정하면 제안을 클릭했을 때 메시지를 자동으로 제출합니다:

'use client';
import * as React from 'react';
import { ChatBox } from '@mui/x-chat';
import { createEchoAdapter } from 'docs/data/chat/core/examples/shared/demoUtils';
import { minimalConversation } from 'docs/data/chat/core/examples/shared/demoData';

const adapter = createEchoAdapter();

export default function AutoSubmitSuggestions() {
  return (
    <ChatBox
      adapter={adapter}
      initialActiveConversationId={minimalConversation.id}
      // Seed only the conversation (no messages) so the empty-state suggestions show.
      initialConversations={[minimalConversation]}
      suggestions={['What can you help me with?', 'Tell me a joke']}
      suggestionsAutoSubmit
      sx={{
        height: 500,
        border: '1px solid',
        borderColor: 'divider',
        borderRadius: 1,
      }}
    />
  );
}

활성 대화에서의 제안

대화에 이미 메시지가 있으면 ChatBox는 제안을 컴포저 위의 가로 스크롤 행으로 계속 보여줍니다. 후속 프롬프트를 제안하는 데 유용해요.

'use client';
import * as React from 'react';
import { ChatBox } from '@mui/x-chat';
import { createEchoAdapter } from 'docs/data/chat/core/examples/shared/demoUtils';
import {
  minimalConversation,
  minimalMessages,
} from 'docs/data/chat/core/examples/shared/demoData';

const adapter = createEchoAdapter();

export default function SuggestionsAboveComposer() {
  return (
    <ChatBox
      adapter={adapter}
      initialActiveConversationId={minimalConversation.id}
      initialConversations={[minimalConversation]}
      initialMessages={minimalMessages}
      suggestions={[
        'Summarize this thread',
        'Make it more formal',
        'Translate to French',
        'Shorten it',
        'Give me an example',
        'What are the next steps?',
      ]}
      sx={{
        height: 500,
        border: '1px solid',
        borderColor: 'divider',
        borderRadius: 1,
      }}
    />
  );
}

ChatBox는 두 배치 사이를 자동으로 전환하며 alwaysVisible prop은 없어요. 독립형 ChatSuggestions 컴포넌트로 커스텀 레이아웃을 구성할 때는 기본적으로 스레드가 비어 있는 동안에만 제안이 렌더링됩니다. 메시지 수와 관계없이 렌더링하려면 alwaysVisible을 설정하세요:

<ChatRoot adapter={adapter}>
  {/* ...message list and composer... */}
  <ChatSuggestions
    suggestions={['Refine the answer', 'Give an example']}
    alwaysVisible
  />
</ChatRoot>

:::info 커스텀 emptyState 슬롯을 제공하면 ChatBox는 빈 상태에서도 제안을 컴포저 위에 렌더링해서 메시지 영역은 여러분의 슬롯에 맡깁니다. :::

제안 비활성화

suggestions prop이 제공되더라도 features prop으로 제안을 비활성화할 수 있어요:

<ChatBox
  adapter={adapter}
  suggestions={['What can you help me with?']}
  features={{ suggestions: false }}
/>

prop 자체를 제거하지 않고 애플리케이션 상태에 따라 조건부로 제안을 보여주고 싶을 때 유용해요.

동적 제안

suggestions는 일반적인 React prop이므로 동적으로 계산할 수 있어요. 아래 예제는 로그인 후 사용자별 제안을 불러와서 이용 가능해지면 업데이트합니다:

function App() {
  const [suggestions, setSuggestions] = React.useState([
    'Get started',
    'View recent activity',
  ]);

  React.useEffect(() => {
    fetchUserSuggestions().then((personalized) => {
      setSuggestions(personalized);
    });
  }, []);

  return <ChatBox adapter={adapter} suggestions={suggestions} />;
}

배열 업데이트는 두 배치 모두에 적용됩니다: 가운데 정렬된 빈 상태 알약과 컴포저 위의 행 모두 새 제안으로 다시 렌더링됩니다.

커스텀 제안 레이아웃 만들기

커스텀 레이아웃을 만들 때는 ChatRoot 프로바이더 안에서 ChatSuggestions를 직접 사용하세요:

import { ChatSuggestions } from '@mui/x-chat';
import { ChatRoot } from '@mui/x-chat/headless';

<ChatRoot adapter={adapter}>
  <ChatSuggestions suggestions={['Option A', 'Option B']} autoSubmit={false} />
</ChatRoot>;

이 컴포넌트는 로컬라이즈 가능한 aria-label(로케일 키 suggestionsLabel, 기본값 "Suggested prompts")을 가진 role="group" 컨테이너를 렌더링해요. 각 제안은 Tab 순서에 있는 일반 <button>이며 Enter 또는 Space로 활성화합니다. 채팅 전체의 키보드 모델은 메시지 목록 키보드 탐색 섹션을 참고하세요.

항목 렌더링을 완전히 가져오려면 suggestions prop 대신 children을 전달하세요. children이 제공되면 suggestions는 무시되고 컴포넌트는 그룹 컨테이너와 선택 컨텍스트만 제공합니다.

<ChatSuggestions>
  <MyCustomSuggestionButton value="Option A" />
  <MyCustomSuggestionButton value="Option B" />
</ChatSuggestions>

슬롯

슬롯 기본값 설명
root 'div' 컨테이너 요소
item 'button' 개별 제안 칩

함께 보기

  • 미리 채워진 값이 텍스트 영역으로 어떻게 흘러가는지에 대한 자세한 내용은 컴포저(Composer)를 참고하세요.
  • 제출된 제안이 백엔드에 어떻게 도달하는지에 대한 자세한 내용은 어댑터(Adapter)를 참고하세요.

ChatSuggestions API

데모

이 React 컴포넌트의 사용에 대한 예시와 자세한 내용은 컴포넌트 데모 페이지를 방문하세요:

가져오기(Import)

import { ChatSuggestions } from '@mui/x-chat/ChatSuggestions';
// or
import { ChatSuggestions } from '@mui/x-chat';

Props

Name Type Default Required Description
alwaysVisible bool false No
autoSubmit bool false No
suggestions Array<{ label?: string, value: string } | string> - No

참고: ref는 루트 요소로 전달됩니다.

제공되는 다른 prop은 모두 루트 요소(네이티브 요소)에 제공됩니다.

CSS

규칙 이름

전체 클래스 규칙 이름 설명
- item 각 제안 항목에 적용되는 스타일.
- root 루트 요소에 적용되는 스타일.

소스 코드

이 페이지에서 정보를 찾지 못했다면 컴포넌트의 구현을 살펴보세요.

더 알아보기 (Learn more)