'Best way to create a search bar with image in results
I want to create a search bar with a list of results including the image and description of the product, I've tried with a datalist component but the html option tag does not allow any other element than text. This component takes the user input, fetch the data to the api and renders a list with the results.
This is my code:
import React, { useEffect, useState } from 'react'
import api from '../../utils/api'
import { baseUrl } from '../../utils/constants'
import styles from './searchBar.module.css'
const SearchBar = () => {
const [search, setSearch] = useState('')
const [results, setResults] = useState([])
useEffect(() => {
const getResults = async () => {
if (search.length > 2) {
try {
const response = await api.post('p/ver-productos', {
cuantos: 10,
filtros: {
nombre: [search],
},
})
if (
response.data.datos.items &&
response.data.datos.items.length > 0
) {
setResults(response.data.datos.items)
} else {
setResults([])
}
} catch (error) {
console.error(error)
setResults([])
}
}
}
getResults()
}, [search])
return (
<>
<input
className={styles.toolbarInput}
placeholder='Buscar productos'
list='results'
value={search}
onChange={e => setSearch(e.target.value)}
/>
<datalist id='results'>
{results.length > 0 &&
results.map((result: any) => {
return (
<option key={result.id}>
<img
src={baseUrl + result.multimedia[0].url}
alt={result.nombre}
/>
{result.nombre}
</option>
)
})}
</datalist>
</>
)
}
export default SearchBar
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
