x clear icon appears only when the input has value - react

Please How can i get the clear x icon that appears only when i start writing in the input field using reactjs like the search input in google page https://www.google.com

import { XIcon } from '@heroicons/react/solid';

export default function Search() {
  const inputElt = useRef(null);

  return (
    <form className='flex'>
     <input
        ref={inputElt}
        className='flex-grow focus:outline-none cursor-pointer'
        type='search'
    />
    <XIcon className='h-5' />
)

Thank you


Solution 1:

You can conditional render the icon based on the value of the input field. Maintain a state for the value using the useState hook. onChange will trigger everytime you enter a value into the input field and set the state.

export default function Search() {
  const inputElt = useRef(null);
  const [value,setValue] = useState('')

  return (
    <form className='flex'>
     <input
        ref={inputElt}
        className='flex-grow focus:outline-none cursor-pointer'
        type='search'
        value={value}
        onChange={(e) =>setValue(e.target.value)}
    />
    {value && <XIcon className='h-5' />}
)
}