Google's search bar has always been a favorite of mine, with its rounded corners and generous text padding.
https://i.stack.imgur.com/UbKrr.png
I'm attempting to replicate this aesthetic using Material UI's <Autocomplete/>
component in my Next.js project, but I'm facing some challenges. Here is what I have so far:
import React, { useState, useEffect } from 'react';
import TextField from '@mui/material/TextField';
import Stack from '@mui/material/Stack';
import Autocomplete from '@mui/material/Autocomplete';
import { borderRadius, Box } from '@mui/system';
import SearchIcon from '@material-ui/icons/Search';
const LiveSearch = (props) => {
const [jsonResults, setJsonResults] = useState([]);
useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/users`)
.then(res => res.json())
.then(json => setJsonResults(json));
}, []);
return (
<Stack sx={{ width: 400, margin: "auto" }}>
<Autocomplete
id="Hello"
getOptionLabel={(jsonResults) => jsonResults.name}
options={jsonResults}
noOptionsText="No results"
isOptionEqualToValue={(option, value) => {
option.name === value.name
}}
renderOption={(props, jsonResults) => (
<Box component="li" {...props} key={jsonResults.id}>
{jsonResults.name} - Ahhh
</Box>
)}
renderInput={(params) => <TextField {...params} label="Search users..." />}
/>
</Stack>
)
}
export default LiveSearch;
The code above should work flawlessly – it includes an axios call to populate the autocomplete results as well.
https://i.stack.imgur.com/cHZMS.png
I have been experimenting with different methods to add the <SearchIcon />
icon prefix inside the input field without success. My main goal, however, is to figure out how to apply padding. In the Google example, the autocomplete aligns perfectly with the box, but in my implementation, the border-radius rounds the element separately, causing misalignment with the dropdown.
Being new to Material UI, I am still learning how to customize styles effectively. It seems that the border is defined by an internal element, making it challenging to adjust padding or borders directly. Despite trying to set styles using sx
, I have not been able to achieve the desired result.