I have a sidebar on my site that has 8 options to filter cars by. Each of the parameters is made in the form of a drop-down list. Parameters are made in various styles - calendar, checkbox, taginput, on/off button.
When the user wants to reset all filters, it is inconvenient for him to return everything to its original position. I would like to add a button that will bring the sidebar to its original position.
I added a very simplified code. Here I create a sidebar, and I prescribe each component (filter) in it.
export default function FiltersSideBar({className}) {
return (
<CardContent className={className}>
<Table>
<TableBody>
<TableRow>
<TableCell>
<Filter1/>
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<Filter2/>
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<Filter3/>
</TableCell>
</TableRow>
<button>Reset All Filters</button>
</TableBody>
</Table>
</CardContent>
);
}
Is there any easy way to reset all filters and reset the sidebar?
CodePudding user response:
Assuming you don't want to use context or redux, you'd have to pull the state up to your FiltersSidebar (i.e. instead of each component handling it's own 'filter value', you keep track of all of that in the parent FiltersSidebar).
So something like:
export default function FiltersSideBar({className}) {
const [filter1Value, setFilter1Value] = useState();
const [filter2Value, setFilter2Value] = useState();
const [filter3Value, setFilter3Value] = useState();
const onResetAll = () => {
setFilter1Value(null);
setFilter2Value(null);
setFilter3Value(null);
}
return (
<CardContent className={className}>
<Table>
<TableBody>
<TableRow>
<TableCell>
<Filter1 value={filter1Value}/>
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<Filter2 value={filter2Value}/>
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<Filter3 value={filter3Value}/>
</TableCell>
</TableRow>
<button onClick={onResetAll}>Reset All Filters</button>
</TableBody>
</Table>
</CardContent>
);
}
CodePudding user response:
You can have a object with the default filter state, and make a functionality that reset the filters wherever you want, so, you can do the following:
// Declare a object with your filters
const defaultFilterState = {
filter1: [],
filter2: [],
filter3: [],
filter4: [],
};
export default function FiltersSideBar({ className }) {
// declare state
const [filters, setFilters] = useState(defaultFilterState);
// Reset all filters
const resetFilters = () => setFilters(defaultFilterState);
return (
<CardContent className={className}>
<Table>
<TableBody>
<TableRow>
<TableCell>
<Filter1 value={filters.filter1} />
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<Filter2 value={filters.filter2} />
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<Filter3 value={filters.filter3} />
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<Filter4 value={filters.filter4} />
</TableCell>
</TableRow>
<button onClick={resetFilters}>Reset All Filters</button>
</TableBody>
</Table>
</CardContent>
);
}