MeDo

Generador de Barra de Búsqueda IA.

Describe qué busca la gente y MeDo genera el widget completo — consultas con debounce, desplegable typeahead, navegación con flechas, búsquedas recientes, estados de carga y sin resultados, y un atajo cmd+K para enfocar.

Barra de búsqueda
Barra de búsqueda

La barra de búsqueda es el único input donde el foco visual y el foco del DOM no coinciden

Todo lo demás en una página mantiene el foco y el resaltado en el mismo lugar. Un typeahead no puede: el cursor debe permanecer en el campo de texto para que se pueda seguir escribiendo, mientras el resaltado baja por la lista de sugerencias. El patrón correcto es aria-activedescendant, donde el input conserva el foco del DOM y apunta a la opción activa por id. Las implementaciones que en su lugar mueven el foco real a la lista rompen la escritura de inmediato, y por eso tantas barras de búsqueda hechas a mano funcionan con el ratón y se desmoronan con el teclado. Generar el campo y la lista como un solo widget significa que esa relación queda conectada desde el principio en lugar de parchearse tras un informe de error.

6 plantillas

Plantillas de Barra de búsqueda que puedes generar

Cada plantilla es un prompt real, no una captura de pantalla. Cópialo en cualquier editor de IA o ejecútalo en MeDo y obtén código React + Tailwind.

BasicInput + Clear

Plain Search Field With Submit

No dropdown, no fetch — just a field that submits to a results page. Start here when the corpus is large enough that suggestions would be guesses rather than shortcuts.

Create a search field: a 40px-tall rounded input inside a real form with role="search", type="search" on the input, enterkeyhint="search" for mobile keyboards, and a visible label or aria-label since a magnifier icon is not an accessible name. Put a 16px magnifier on the left with aria-hidden, and a clear button on the right that appears only once there is text, is a real button with an accessible label, and returns focus to the input after clearing. Enter submits the raw query through the form so search still works with JavaScript disabled. Escape clears the field when it has text. Show a focus-visible ring on the wrapper, not the bare input, so the icon and field read as one control.

Prueba en MeDo
ComboboxTypeahead

Debounced Suggestions Listbox

The full combobox: debounce, listbox, aria-activedescendant. The critical rule is that DOM focus never leaves the input, or typing stops working the moment someone presses Arrow Down.

Create a typeahead search bar using the ARIA combobox pattern: aria-expanded, aria-controls and aria-activedescendant on the input, role="listbox" on the panel, role="option" with a unique id on each row. DOM focus must stay in the text field at all times — move the visual highlight by updating aria-activedescendant, never by focusing an option, or typing breaks. Debounce queries at 250ms and cancel in-flight requests so a slow earlier response cannot overwrite a newer one. Arrow Down and Up move the active option and wrap at the ends, Home and End jump to the first and last, Enter selects the active option or submits the raw query when none is active, Escape closes the panel and restores the typed text, and Tab closes and moves on rather than walking the options.

Prueba en MeDo
cmd+KCommand Palette

Modal Search Overlay

Search as primary navigation, opened from anywhere with cmd+K. It is a modal dialog, which means a focus trap and focus restoration — the part most palette clones skip.

Create a command-palette search overlay opened by cmd+K and ctrl+K: a centered dialog with a backdrop, using the native dialog element or role="dialog" with aria-modal="true". Trap focus inside it, place initial focus in the input, close on Escape and backdrop click, and return focus to the element that was focused before opening. Ignore the shortcut while the user is typing in another input or a contenteditable region. Inside, run the ARIA combobox pattern with aria-activedescendant, group results under headed sections such as Pages, Docs and Actions, and let Arrow Down and Up move across group boundaries while skipping the group headings. Show a visible cmd+K hint in the trigger and keyboard hints in the dialog footer.

Prueba en MeDo
StatesRecent + Empty

Search With Recent Queries and No-Results

Three panels, not one: recent searches on an empty query, skeleton rows in flight, a no-results row with a fallback. Leave any out and the dropdown flickers blank between keystrokes.

Create a search bar that renders three distinct dropdown states rather than one panel that empties. On an empty query, show up to five recent searches from localStorage under a Recent heading, each with a small remove button and a Clear all action. While a request is in flight, keep the previous results visible and overlay three skeleton rows, and swap the magnifier for an inline spinner rather than blanking the panel. On zero matches, show a no-results row naming the query plus a "Search everything" fallback action that submits the raw text. Announce the outcome in an aria-live="polite" region — "8 results available" or "No results" — debounced so intermediate counts are not read out. Arrow keys, Enter and Escape behave identically in all three states.

Prueba en MeDo
FiltersScoped Search

Search With Scope Chips and Filters

A scope chip inside the field narrows the query before it runs. Make Backspace on an empty query remove the chip — anything else and people are hunting for a tiny × with the mouse.

Create a scoped search bar: removable scope chips render inside the input wrapper to the left of the text caret, each a button with an accessible label such as "Remove filter: Invoices". Pressing Backspace with an empty query removes the last chip rather than doing nothing, and typing a known prefix followed by a colon converts it into a chip. Keep the chips out of the input value itself and send them as separate query parameters. Below the field, render filter pills that are toggle buttons with aria-pressed, and re-run the debounced query on every change. Preserve the caret position when a chip is added, keep the ARIA combobox wiring for the suggestion listbox, and reflect the active scope in the aria-live result-count announcement.

Prueba en MeDo
Media rowsRich Results

Suggestions With Thumbnails and Prices

Product and media rows where each suggestion carries an image, title and price. Reserve the thumbnail box explicitly, or every keystroke reflows the panel as images resolve.

Create a search bar with rich suggestion rows: each row is a role="option" containing a 40px thumbnail with explicit width and height attributes so the panel does not reflow as images load, a title with the matched substring bolded, and a secondary line with price or category. Because the row holds several elements, give each option an aria-label describing the whole row so a screen reader hears one coherent option rather than fragments. Cap the panel at 320px with internal scroll, and scroll the active option into view with block nearest as aria-activedescendant moves. Keep the last row a "See all results for <query>" action that submits the raw text. Highlight matches by wrapping the substring, never by injecting HTML from the response.

Prueba en MeDo

Cómo personalizar tu Barra de búsqueda

Nombra el intervalo de debounce

Di "debounce a 250ms" en lugar de "aplica debounce al input". Por debajo de unos 150ms lanzas una petición por pulsación; pasados unos 400ms el desplegable parece roto. Combínalo con cancelación para que una respuesta anterior lenta no sobrescriba una más reciente.

Describe los tres estados vacíos por separado

Consulta vacía, consulta en curso y cero resultados son tres pantallas distintas. Pide búsquedas recientes en la primera, un spinner o filas skeleton en la segunda, y una fila de sin resultados con una acción de respaldo en la tercera. Si omites alguna, obtienes un panel que parpadea en blanco.

Indica si Enter envía o selecciona

Con una sugerencia resaltada, Enter debe seleccionarla; sin nada resaltado, Enter debe enviar la consulta cruda a una página de resultados. Detalla ambas ramas y pide un formulario real con role="search" para que la ruta de envío funcione sin JavaScript.

Pide que se anuncie el número de resultados

Los usuarios videntes ven crecer la lista. Los usuarios de lector de pantalla necesitan una región aria-live="polite" que diga algo como "8 resultados disponibles". Solicita la región live explícitamente y pide que también tenga debounce para que no lea cada recuento intermedio.

Quién usa el componente Barra de búsqueda

Sitio de documentación

Una barra de búsqueda con cmd+K que se abre sobre la página, agrupa los resultados por sección, muestra la línea coincidente bajo cada título y guarda las últimas cinco consultas para volver a una página que se recuerda a medias.

Tienda de comercio electrónico

Sugerencias de producto con miniatura, nombre y precio por fila, atajos de categoría encima y una fila final de "Ver todos los resultados de..." que envía la consulta cruda a la página completa de resultados.

Panel o herramienta de administración

Un solo campo que busca entre clientes, facturas y ajustes, con resultados agrupados por tipo y un chip de alcance en el input para poder limitar a una única entidad antes de escribir.

Biblioteca de contenido o medios

Una barra de búsqueda ancha con píldoras de filtro al lado, filas skeleton mientras corre la consulta y un estado de sin resultados que sugiere correcciones ortográficas en lugar de mostrar un panel vacío.

Patrones de Barra de búsqueda para distintos sitios web

El mismo componente barra de búsqueda, adaptado al tipo de sitio donde se publica.

01 / 06

Documentation Search

A cmd+K palette that groups hits by section and shows the matching line under each title, since a page title alone rarely tells a reader whether the answer is on it. Keep the last five queries — docs search is mostly people returning to a page they half remember.

Estilos y variantes de Barra de búsqueda

Elige la variante que encaje con el resto de la página y genérala.

01 / 06

Inline Field Search

A permanent bordered input in the header or page body. The most discoverable option and the only one that works without JavaScript, since a real form with role="search" submits on Enter regardless. Give the wrapper the focus ring so the icon and field read as one control.

Barra de búsqueda en React, Next.js, Vue y Svelte

React, Next.js, Vue 3, SvelteKit, Astro o HTML puro: el mismo barra de búsqueda, seis formas de integrarlo.

01 / 06

React Search Bar

Track the active index as a number and derive aria-activedescendant from it — that is the entire highlight mechanism, with no focus moves. Abort the previous fetch in the effect cleanup so a slow response cannot land after a newer one.

src/components/SearchBar.tsx

const [active, setActive] = useState(-1)
const debounced = useDebounce(query, 250)

<input
  type="search"
  role="combobox"
  aria-expanded={open}
  aria-controls="search-listbox"
  aria-activedescendant={active >= 0 ? `opt-${active}` : undefined}
  onKeyDown={onArrowKeys}
/>

Cómo añadir tu Barra de búsqueda a un proyecto

Cuatro pasos, desde elegir una plantilla de barra de búsqueda hasta llevarlo a producción.

01~30s

Pick a Search Pattern

Decide whether you need suggestions at all. A plain field posting to a results page is often the honest answer; reach for the typeahead or the cmd+K palette only when search is a primary navigation path.

02~10s

Copy the Prompt

Take the prompt into MeDo, Lovable, Bolt, v0 or Cursor, then set two numbers: the debounce interval and how many suggestions the panel shows. Name what is being searched too, since that decides how a result row is shaped.

03~1min

Generate and Refine

You get React + Tailwind back with a live preview. Follow up in plain English — "add recent searches", "group results by type", "announce the result count politely" — rather than rewriting the keydown handler.

04~2min

Connect Your Index and Ship

Point the query at your real endpoint, then test with the keyboard only: type, Arrow Down, Enter, Escape. If typing stops working after Arrow Down, focus was moved into the list and the highlight needs to go back to aria-activedescendant.

Preguntas frecuentes sobre Barra de búsqueda

¿Cómo genero una barra de búsqueda con IA?

Describe qué se busca, de dónde vienen las sugerencias y qué estados necesitas — búsquedas recientes, carga, sin resultados. MeDo genera el input, el desplegable de sugerencias, el manejo de consultas con debounce y los atajos de teclado como un solo componente en lugar de un campo de texto pelado que tengas que conectar después.

¿Cuál es la diferencia entre una barra de búsqueda y un autocompletar?

Una barra de búsqueda envía una consulta de texto libre y trata las sugerencias como atajos, así que escribir algo sin coincidencias sigue siendo válido. Un autocompletar restringe el valor a una lista, por lo que el input solo se confirma al elegir una opción. La distinción cambia el marcado: una barra de búsqueda va en un formulario con role="search", mientras un autocompletar restringido es un combobox ligado a un valor de formulario.

¿Puede la IA generar una barra de búsqueda accesible?

Sí, si pides el patrón por su nombre. MeDo implementa el patrón ARIA combobox con aria-expanded, aria-controls y aria-activedescendant en el input, role="listbox" y role="option" en el panel, y una región live polite para el número de resultados. El foco permanece en el campo de texto todo el tiempo, que es lo que mantiene funcionando juntos la escritura y las flechas.

¿Cómo debe funcionar la navegación por teclado en un desplegable de búsqueda?

Flecha abajo pasa a la primera sugerencia y continúa bajando la lista, flecha arriba retrocede y puede devolver el foco a la consulta cruda, Enter selecciona el elemento resaltado y Escape cierra el panel restaurando lo que la persona escribió. Inicio y Fin son una adición útil para listas largas. Tab debería cerrar el panel y avanzar, no recorrer las opciones.

¿Debo usar type="search" en el input?

Sí. Te da el botón de borrado nativo del navegador en algunas plataformas, señala la intención a las tecnologías de asistencia y combina con un enterkeyhint de "search" en los teclados móviles. Envuélvelo en un formulario real con role="search" para que la consulta siga enviándose si falla el scripting, y da al input una etiqueta o aria-label, ya que un icono de lupa por sí solo no es un nombre accesible.

¿Necesita una barra de búsqueda un atajo cmd+K?

Ayuda donde la búsqueda es una vía de navegación principal, como documentación, paneles y herramientas para desarrolladores. Vincula tanto cmd+K como ctrl+K, ignora el atajo mientras el usuario escribe en otro input y muestra la pista dentro del campo para que sea descubrible. Menciónalo en tu prompt a MeDo y el listener junto con la pista visible se generan a la vez.