Skip to content

Material 3

Components

Search

Search lets people enter a keyword or phrase to get relevant information.

9:30
Recent searches
Peanut butter recipes
Pet adoption
Movie marathon
Weekend hike
Book club

Search lets people enter a keyword or phrase to get relevant information. Use it where finding content is a primary task. For a field that takes other text, use a text field instead.

Search has two parts:

PartUse
SearchFieldThe search bar, to search the contents of a view, like Search your messages
SearchViewThe focused search, for the suggestions or results that a search bar opens
import { Icon, IconButton, List, ListItem, SearchField, SearchView } from '@material-web/react'
import { Autocomplete, Input, Text, useFilter } from 'react-aria-components'

Write a SearchField for the search bar in the page, and a SearchView for the focused search that it opens. In the SearchView, write a second SearchField and, below it, what you show, typically a List. Wrap the two in React Aria's Autocomplete to filter the list as the query is typed.

import { Icon, IconButton, List, ListItem, SearchField, SearchView } from '@material-web/react'
import { useRef, useState } from 'react'
import { Autocomplete, Input, Text, useFilter } from 'react-aria-components'

const suggestions = [
  ['Peanut butter recipes', 'history'],
  ['Pet adoption', 'history'],
  ['Movie marathon', 'history'],
  ['Weekend hike', 'search'],
  ['Book club', 'search'],
  ['Flight tickets', 'search'],
] as const

export default function Basic() {
  const [query, setQuery] = useState('')
  const [isOpen, setOpen] = useState(false)
  const bar = useRef<HTMLDivElement>(null)
  const { contains } = useFilter({ sensitivity: 'base' })
  return (
    <div className="h-64 w-full pt-space-300">
      <SearchField
        ref={bar}
        aria-label="Search your messages"
        value={query}
        onChange={(value) => {
          setQuery(value)
          setOpen(true)
        }}
        onClick={() => setOpen(true)}
        className="mx-space-300"
      >
        <Icon slot="leading" name="search" />
        <Input placeholder="Search your messages" />
        <IconButton slot="trailing" aria-label="Voice search">
          <Icon name="mic" />
        </IconButton>
      </SearchField>
      <SearchView
        aria-label="Search your messages"
        triggerRef={bar}
        isOpen={isOpen}
        onOpenChange={setOpen}
      >
        {({ state }) => (
          <Autocomplete
            inputValue={query}
            onInputChange={setQuery}
            filter={contains}
            disableAutoFocusFirst
          >
            <SearchField autoFocus aria-label="Search your messages" onSubmit={state.close}>
              <Icon slot="leading" name="search" />
              <IconButton slot="leading" aria-label="Back" onPress={state.close}>
                <Icon name="arrow_back" />
              </IconButton>
              <Input placeholder="Search your messages" />
              <IconButton aria-label="Clear search">
                <Icon name="close" />
              </IconButton>
            </SearchField>
            <List
              aria-label="Suggestions"
              onAction={(key) => {
                setQuery(String(key))
                state.close()
              }}
            >
              {suggestions.map(([label, icon]) => (
                <ListItem key={label} id={label} textValue={label}>
                  <Icon slot="leading" name={icon} />
                  <Text slot="label">{label}</Text>
                </ListItem>
              ))}
            </List>
          </Autocomplete>
        )}
      </SearchView>
    </div>
  )
}

Write the parts of the bar as the children of a SearchField. They are shown in the order written. Their places are listed under Slots.

import { Icon, IconButton, SearchField } from '@material-web/react'
import { Input } from 'react-aria-components'

const avatar = `data:image/svg+xml,${encodeURIComponent(
  '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 30 30"><rect width="30" height="30" fill="#6750a4"/><text x="15" y="20" font-family="sans-serif" font-size="14" fill="#fff" text-anchor="middle">A</text></svg>',
)}`

export default function SearchBars() {
  return (
    <div className="flex w-full flex-col gap-space-300">
      <SearchField aria-label="Search your messages">
        <Icon slot="leading" name="search" />
        <Input placeholder="Search your messages" />
        <IconButton aria-label="Clear search">
          <Icon name="close" />
        </IconButton>
      </SearchField>
      <SearchField aria-label="Search your messages">
        <IconButton slot="leading" aria-label="Menu">
          <Icon name="menu" />
        </IconButton>
        <Input placeholder="Search your messages" />
        <IconButton slot="trailing" aria-label="Voice search">
          <Icon name="mic" />
        </IconButton>
        <IconButton slot="trailing" aria-label="Account">
          <img src={avatar} alt="" />
        </IconButton>
      </SearchField>
      <SearchField aria-label="Search your messages">
        <Input placeholder="Search your messages" />
      </SearchField>
    </div>
  )
}

The bar is 56dp tall and fills the width available to it, up to 720dp, and is at least 360dp wide where there is room. In a page, add its 24dp side margins yourself with mx-space-300.

Pressing the bar outside its controls focuses the input.

Slots

  1. leading
  2. trailing
SlotChildUse
leadingAn Icon or an IconButtonBefore the input
trailingAn Icon or an IconButtonAfter the input

A bar also takes these parts:

PartUse
InputThe text field. Set its placeholder to the hinted search text.
A button with no slotThe clear button. It is shown while there is text, and clears it. A button in the leading or trailing slot does not clear the text.
<img>, on its own or in an IconButtonShown as a round avatar

A SearchView is modal, like a dialog. Its props are isOpen, defaultOpen and onOpenChange, layout, variant, triggerRef and aria-label.

As its children, write a SearchField with autoFocus, then typically a List, both in an Autocomplete, as in the first example. children can also be a function of isEntering, isExiting and state. Call state.close() to close the view.

In the view's bar, write the icon of the page's bar first, before the back button, as the example does. The view shows that icon where the page's bar has it, and cross-fades it with the back button.

Opening

You decide what opens focused search, and when it shows suggestions or results. The first example opens it when the bar is pressed or text is typed. You can also open it on the Down arrow in onKeyDown, or in onSubmit once a query is entered.

A SearchView also opens from the button of a DialogTrigger, such as the Button in the search slot of a search app bar. Wrap the DialogTrigger around that button and the SearchView alone: any other button in the trigger would open the view too.

import {
  AppBar,
  Icon,
  IconButton,
  List,
  ListItem,
  SearchField,
  SearchView,
} from '@material-web/react'
import { useState } from 'react'
import { Button, DialogTrigger, Input } from 'react-aria-components'

const recent = ['Peanut butter recipes', 'Pet adoption', 'Movie marathon']

export default function FromAnAppBar() {
  const [query, setQuery] = useState('')
  return (
    <div className="h-64">
      <AppBar className="text-center">
        <IconButton slot="leading" aria-label="Menu">
          <Icon name="menu" />
        </IconButton>
        <DialogTrigger>
          <Button slot="search">
            <Icon slot="leading" name="search" />
            {query || 'Search your messages'}
          </Button>
          <SearchView aria-label="Search your messages">
            {({ state }) => (
              <>
                <SearchField
                  autoFocus
                  aria-label="Search your messages"
                  value={query}
                  onChange={setQuery}
                  onSubmit={state.close}
                >
                  <Icon slot="leading" name="search" />
                  <IconButton slot="leading" aria-label="Back" onPress={state.close}>
                    <Icon name="arrow_back" />
                  </IconButton>
                  <Input placeholder="Search your messages" />
                  <IconButton aria-label="Clear search">
                    <Icon name="close" />
                  </IconButton>
                </SearchField>
                <List
                  aria-label="Recent searches"
                  onAction={(key) => {
                    setQuery(String(key))
                    state.close()
                  }}
                >
                  {recent.map((label) => (
                    <ListItem key={label} id={label}>
                      {label}
                    </ListItem>
                  ))}
                </List>
              </>
            )}
          </SearchView>
        </DialogTrigger>
        <IconButton slot="trailing" aria-label="Account">
          <Icon name="account_circle" />
        </IconButton>
      </AppBar>
    </div>
  )
}

Set triggerRef to the element the view opens from, typically the page's search bar. The view takes its position and width from that element. In a DialogTrigger without a triggerRef, the view opens from the trigger's button. With neither, it fades in and out, docked at the top of the window.

Layout

Set layout to docked (the default) or full-screen. Use full-screen in compact windows and docked in larger ones, and switch between them by the window's size.

  • docked opens over the bar that opened it, at the same width. It is at least 240dp tall and at most two thirds of the window's height, and it ends 12dp above the bottom of the window where the bar is near that edge.
  • full-screen fills the window, with its bar at the top.
import { Icon, IconButton, List, ListItem, SearchField, SearchView } from '@material-web/react'
import { useRef, useState } from 'react'
import { Input } from 'react-aria-components'

const recent = ['Peanut butter recipes', 'Pet adoption', 'Movie marathon']

export default function FullScreen() {
  const [query, setQuery] = useState('')
  const [isOpen, setOpen] = useState(false)
  const bar = useRef<HTMLDivElement>(null)
  return (
    <>
      <SearchField
        ref={bar}
        aria-label="Search your messages"
        value={query}
        onChange={(value) => {
          setQuery(value)
          setOpen(true)
        }}
        onClick={() => setOpen(true)}
        className="w-full"
      >
        <Icon slot="leading" name="search" />
        <Input placeholder="Search your messages" />
      </SearchField>
      <SearchView
        aria-label="Search your messages"
        layout="full-screen"
        triggerRef={bar}
        isOpen={isOpen}
        onOpenChange={setOpen}
      >
        {({ state }) => (
          <>
            <SearchField
              autoFocus
              aria-label="Search your messages"
              value={query}
              onChange={setQuery}
              onSubmit={state.close}
            >
              <Icon slot="leading" name="search" />
              <IconButton slot="leading" aria-label="Back" onPress={state.close}>
                <Icon name="arrow_back" />
              </IconButton>
              <Input placeholder="Search your messages" />
              <IconButton aria-label="Clear search">
                <Icon name="close" />
              </IconButton>
            </SearchField>
            <List
              aria-label="Recent searches"
              onAction={(key) => {
                setQuery(String(key))
                state.close()
              }}
            >
              {recent.map((label) => (
                <ListItem key={label} id={label}>
                  {label}
                </ListItem>
              ))}
            </List>
          </>
        )}
      </SearchView>
    </>
  )
}

Style

Set variant to choose the style:

  • contained (the default) keeps the bar in its own container, with the list in a separate container below it. When docked, it opens over a scrim.
  • divided shows the bar and the list in one container, with a divider between them. When docked, it has no scrim.
import { Icon, IconButton, List, ListItem, SearchField, SearchView } from '@material-web/react'
import { useRef, useState } from 'react'
import { Input } from 'react-aria-components'

const recent = ['Peanut butter recipes', 'Pet adoption', 'Movie marathon']

export default function Divided() {
  const [query, setQuery] = useState('')
  const [isOpen, setOpen] = useState(false)
  const bar = useRef<HTMLDivElement>(null)
  return (
    <>
      <SearchField
        ref={bar}
        aria-label="Search your messages"
        value={query}
        onChange={(value) => {
          setQuery(value)
          setOpen(true)
        }}
        onClick={() => setOpen(true)}
        className="w-full"
      >
        <Icon slot="leading" name="search" />
        <Input placeholder="Search your messages" />
      </SearchField>
      <SearchView
        aria-label="Search your messages"
        variant="divided"
        triggerRef={bar}
        isOpen={isOpen}
        onOpenChange={setOpen}
      >
        {({ state }) => (
          <>
            <SearchField
              autoFocus
              aria-label="Search your messages"
              value={query}
              onChange={setQuery}
              onSubmit={state.close}
            >
              <Icon slot="leading" name="search" />
              <IconButton slot="leading" aria-label="Back" onPress={state.close}>
                <Icon name="arrow_back" />
              </IconButton>
              <Input placeholder="Search your messages" />
              <IconButton aria-label="Clear search">
                <Icon name="close" />
              </IconButton>
            </SearchField>
            <List
              aria-label="Recent searches"
              onAction={(key) => {
                setQuery(String(key))
                state.close()
              }}
            >
              {recent.map((label) => (
                <ListItem key={label} id={label}>
                  {label}
                </ListItem>
              ))}
            </List>
          </>
        )}
      </SearchView>
    </>
  )
}

Keyboard and focus

Set autoFocus on the view's bar. When focused search opens, the focus moves to that bar, with the query in it.

  • Tab moves the focus into the list. The arrow keys move through the items, Enter acts on the focused item, and Shift+Tab returns to the bar.
  • Typing does not focus an item, so Enter in the bar submits the query as typed. A List behaves this way on its own. For a listbox, set disableAutoFocusFirst on the Autocomplete, as the example does.
  • Escape clears the bar first, then closes the view. A press outside a docked view closes it too, and so does a back button of yours that calls state.close().
  • When the view closes, the focus returns to the element that opened it.

While the view is open, the page behind it is inert and does not scroll.

Handling input

The bar reports the query as it changes and when it is entered:

EventCalled
onChangeWith the query, as it is typed or cleared
onSubmitWith the query, on Enter
onClearWhen Escape or the clear button empties the bar

Value: none. Submitted: none.

import { Icon, IconButton, SearchField } from '@material-web/react'
import { useState } from 'react'
import { Input } from 'react-aria-components'

export default function Controlled() {
  const [value, setValue] = useState('')
  const [submitted, setSubmitted] = useState('')
  return (
    <div className="flex w-full flex-col gap-space-200">
      <SearchField
        aria-label="Search your messages"
        value={value}
        onChange={setValue}
        onSubmit={setSubmitted}
        onClear={() => setSubmitted('')}
      >
        <Icon slot="leading" name="search" />
        <Input placeholder="Search your messages" />
        <IconButton aria-label="Clear search">
          <Icon name="close" />
        </IconButton>
      </SearchField>
      <p className="m-0 text-body-md text-on-surface-variant">
        Value: {value || 'none'}. Submitted: {submitted || 'none'}.
      </p>
    </div>
  )
}

Controlled

Search has two states, each controlled on its own component:

  1. Query: Set the initial query of a SearchField with defaultValue, or control it with value and onChange.
  2. Open state: Control a SearchView with isOpen and onOpenChange, or set defaultOpen.
const [query, setQuery] = useState('')
const [isOpen, setOpen] = useState(false)

<SearchField value={query} onChange={setQuery}>
  {/* ... */}
</SearchField>
<SearchView isOpen={isOpen} onOpenChange={setOpen}>
  {/* ... */}
</SearchView>

The page's bar and the view's bar show the same query. Give both the same value, or control the view's Autocomplete with inputValue and onInputChange, as the first example does.

Custom filter

An Autocomplete shows the items that its filter accepts. filter is called with the text of an item and the query, and returns whether the item matches. React Aria's useFilter provides contains, startsWith and endsWith, which compare text in the locale. The first example uses contains, without regard to case.

const { startsWith } = useFilter({ sensitivity: 'base' })

<Autocomplete filter={startsWith}>
  {/* ... */}
</Autocomplete>

Give each item a textValue when its children are not plain text. Without an Autocomplete, the list is not filtered: show the items you choose, such as recent searches.

Disabled

Set isDisabled to disable the bar. Its leading and trailing buttons are disabled with it, unless one sets isDisabled={false} itself. A SearchField also takes isReadOnly, isRequired and name.

import { Icon, IconButton, SearchField } from '@material-web/react'
import { Input } from 'react-aria-components'

export default function Disabled() {
  return (
    <SearchField
      aria-label="Search your messages"
      defaultValue="Weekend hike"
      isDisabled
      className="w-full"
    >
      <IconButton slot="leading" aria-label="Menu">
        <Icon name="menu" />
      </IconButton>
      <Input placeholder="Search your messages" />
      <IconButton aria-label="Clear search">
        <Icon name="close" />
      </IconButton>
      <IconButton slot="trailing" aria-label="Voice search">
        <Icon name="mic" />
      </IconButton>
    </SearchField>
  )
}

Customization

Pass classes in className to restyle one bar. A class of yours replaces the bar's own class for the same property. See Styling for the classes, the states and the theme.

In this example, rounded-shape-lg replaces the bar's round corners, and the voice search button is shown only while the bar is empty.

import { Icon, IconButton, SearchField } from '@material-web/react'
import { Input } from 'react-aria-components'

export default function Custom() {
  return (
    <SearchField aria-label="Search your messages" className="w-full rounded-shape-lg">
      {({ isEmpty }) => (
        <>
          <Icon slot="leading" name="search" />
          <Input placeholder="Search your messages" />
          <IconButton aria-label="Clear search">
            <Icon name="close" />
          </IconButton>
          {isEmpty && (
            <IconButton slot="trailing" aria-label="Voice search">
              <Icon name="mic" />
            </IconButton>
          )}
        </>
      )}
    </SearchField>
  )
}
  • Width: In a flex row, a bar is 360dp wide: add w-full to make it fill the row. Add max-w-none to let a bar grow past 720dp.
  • Input: The Input takes classes of its own, such as a text color.
  • States: On the bar, style the empty, disabled, invalid, read-only and required states with their variants, such as disabled:, or with data-empty and the like in your own CSS. Hover and focus are reported on the input: use the has-* form for them, as in has-hover:bg-surface-container. See Variants.
  • Functions: className, style and children can be functions of the bar's state: isEmpty, isDisabled, isInvalid, isReadOnly, isRequired and state. See Children as a function.
  • Every bar: To restyle all the search bars at once, change the theme.

Limitations

Search app bar

Give the search bar of a search app bar a search icon in its leading slot. Without one, its text jumps as the view opens and closes.

View styling

A SearchView takes no className or style. Its look comes from layout and variant, and from the bar and the list you write in it.