Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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' />}
)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading