Reactjs change value when its clicked

Viewed 66

I have a variable id that has already had value, I just want that if the user click the ClearIcon the id will turn to null. so that he does not become equal to location.id

  const [getId, setId] = useState(id)
  
  const stopSearching = () => {
    setId(null)
  };
  <IconButton onClick={stopSearching} edge="end">
    <ClearIcon />
  </IconButton>
  {console.log(getId)}
  {filteredLocations.map((location, index) => (
     <LocationWidgetItem
        key={index}
        location={location}
        onClickLocation={setActiveLocation}
          selectedLocation={location.id ==getId}
     />
  ))}
2 Answers

Is id a state variable?

Note: id === null is for equality comparison.

If is a state variable like

const [id, setId] = useState(initialValue);

then do it like this:

const stopSearching = () => {
    setId(null)
  };

If it is not a state variable, then to trigger rerender, it need to be a prop and there must be some function to change id prop.


Since I can't understand the query exactly, it will be better to add your code in codesandbox.io.

For now, I am adding a method,

const [getId, setId] = useState(0);
//I am taking id 0 as initial value, you can pick any other value
  
  const setActiveLocation = (id) => {
    setId(id);
  }
  const stopSearching = () => {
    setId(null)
  };
  <IconButton onClick={stopSearching} edge="end">
    <ClearIcon />
  </IconButton>
  {console.log(getId)}
  {filteredLocations.map((location, index) => (
     <LocationWidgetItem
        key={index}
        location={location}
        onClickLocation={() => setActiveLocation(location.id)}
          selectedLocation={location.id === getId}
     />)}

I think you have to set it with setId

const stopSearching = () => {
    setId(null)
};

so that will automatically invalidate the previous content and will set the

    selectedLocation={location.id ==getId}

to false

Related