Is there a way to clear the selected value on radix-ui's select component?

578 Views Asked by At

I'm using radix-ui's select component to filter data on my reactjs app, but I was wondering how do I clear one selected value without having to refresh the page.

I tried to change the function that handle the changes to this below, but it never gets to that if condition. It's like the component totally ignores when the option doesn't change:

const handleChangeProject = (value) => {
    if( value === selectedProject){
      console.log("IM HERE")
      setSelectedProject(null);
    }else{
      setSelectedProject(value);
      console.log(value);
      setFilteredDocs(
        docs.filter((doc) =>
          doc?.project.toLowerCase().includes(value.toLowerCase())
        )
      );
    }
  };

Here's the radix-ui component in action:


<Select value={selectedProject} onValueChange={handleChangeProject}>
   <SelectTrigger className="w-[180px]">
       <SelectValue placeholder="Projects" />
   </SelectTrigger>
   <SelectContent>
       <SelectGroup>
           <SelectLabel>Projects</SelectLabel>
           {projects.map((project) => (
               <SelectItem
                  key={project.project_name}
                  value={project.project_name}
               >
                  {project.project_name}
               </SelectItem>
           ))}
       </SelectGroup>
    </SelectContent>
</Select>
1

There are 1 best solutions below

0
Alexey Balakhanov On
<Select 
    defaultValue={selectedProject}
    value={selectedProject} 
    onValueChange={handleChangeProject}
>

Try to add defaultValue and set selectedProject to it. Then to clear input you should set empty string to it.

const [selectedProject, setSelectProject] = useState<undefined | string>(undefined)
const clearSelectandler = () => {
    ...
    setSelectedProject("")
    ...
}