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

React TextField with collapse

How to hide the lists of cities when the textfield is empty and when the user start typing the lists will show.

https://codesandbox.io/s/loving-platform-t2cyb?file=/src/LocationWidget.js

  const openSearch = () => {
    setViewLocationList(true);
    startSearch();
  };
  const stopSearch = () => {
    setSearchParameter('')
    setViewLocationList(false);
  };


  <TextField
    variant="outlined"
      placeholder="Search Locations"
      onFocus={openSearch}
      onChange={filterResults}
      value={searchParameter}
      classes={{notchedOutline:classes.input}}
      InputProps={{
        endAdornment: (
          <IconButton onClick={stopSearch} edge="end">
            <ClearIcon />
          </IconButton>
        ),
        classes:{notchedOutline:classes.noBorder},
        startAdornment: (
          <InputAdornment position="start">
            <SearchIcon />
          </InputAdornment>
        ),
      }}
    />
  </Box>
  <Collapse in={viewLocationList} sx={{ my: '2px' }}>
    <Box className="rounded-scrollbar widget-result-container">
    {filteredLocations.map((location, index) => (
         <LocationWidgetItem
         key={index}
         location={location}
         onClickLocation={setActiveLocation}
       />
      ))}
    </Box>
  </Collapse>

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 have to take state variable in which you have to store whatever user is typing:

const [text,setText] = useState("");

and in your filterLocations you have to update its value

const filterLocations = (txt) => {
    setText(txt.target.value);  
    let filteredLocations = locations.filter((e) =>
    e.name.toLowerCase().includes(txt.target.value.toLowerCase())
    );
    setSearchParameter(filteredLocations);
  };

And Finally in your render, render ul conditioanlly

{ !!text && <ul>
        {searchParameter.map((location) => (
          <li key={location.name}>{location.name}</li>
        ))}
      </ul>}

https://codesandbox.io/s/dreamy-roentgen-0jnoi?file=/src/LocationWidget.js

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