Home > Enterprise >  React search or filter from lists of locations
React search or filter from lists of locations

Time:12-28

I have a list of locations that shows when the textfield onfocus, what i want is when the user starting typing in the textfield it will start searching or filter in the lists of locations stored in variable locations. I have successfully showing the lists of location, the problem i have is the filtering or search within the lists of locations

const propTypes = {
  locations: PropTypes.array,
  setActiveLocation: PropTypes.func,
  setViewLocationList: PropTypes.func,
  startSearch: PropTypes.func,
  viewLocationList: PropTypes.bool,
};
const defaultProps = {
  locations: [],
  setActiveLocation: () => {},
  setViewLocationList: () => {

  },
  startSearch: () => {},
  viewLocationList: false,
};

const LocationSearchWidget = ({
  locations,
  viewLocationList,
  setViewLocationList,
  setActiveLocation,
  startSearch,
}) => {
  const [searchParameter, setSearchParameter] = useState(locations);
  const onChangeLocation = (event) => {
    setSearchParameter(event.target.value)
    locations.filter(l => l.name === searchParameter).map(filteredLocation => (
      locations = filteredLocation
    ))
  };
  return (
    <div className="widget-container">
      <Box
        component="form"
        noValidate
        autoComplete="off"
        className="filter-container"
      >
        <TextField
          size="small"
          fullWidth
          name="locationName"
          onChange={onChangeLocation}
          variant="standard"
          placeholder="Search Locations"
          onFocus={openSearch}
          value={searchParameter}
     
          }}
        />
      </Box>
      <Collapse in={viewLocationList} sx={{ my: '2px' }}>
        <Box className="rounded-scrollbar widget-result-container">
          {locations.map((location, index) => (
            <LocationWidgetItem
              key={index}
              location={location}
              onClickLocation={setActiveLocation}
            />
          ))}
        </Box>
      </Collapse>
    </div>
  );
};

nothing happen in the lists of location even i type in TextField

original locations in the variable named locations

CodePudding user response:

const [locations,setLocations] = useState(copy of original location)

pass setLocations as prop to LocationSearchWidget as well as OriginalLocations and then change

locations.filter(l => l.name === searchParameter).map(filteredLocation => (
  location = filteredLocation
))

to

setLocations(OriginalLocations.filter(l => l.name === searchParameter).map(filteredLocation => (
  location = filteredLocation
)))

Demo: https://codesandbox.io/s/goofy-rgb-s53h1

  • Related