How to filter Table data using DropDown selection in NextJs

How to filter Table data using DropDown selection in NextJs

I cam acrross an interesting feature to add in my last project. New feature to be implemented consist of two different React component, one is a dropdown list and another one is a simple table.

The trick here is to put in comunication the two components and each of them has two different APIs calls. The the table has to be filtered based on the future selection in dropdown list.

In this article I’ll describe step by step how you can implement it.

DropDown component:

export default function DropDownComponent({ onDataChange }: Prop) {
    const [sessions, setSessions] = useState<CodeSession[]>([]);
    const [selectedRecordID, setselectedRecordID] = useState<number>();

    function fetchData() {
        setLoading(true);
        GetData().then((data) => {
            if (data.length > 0) {
                setSelectedSessionID(sessionId);
                onSessionChange(sessionId);
            }
            setData(data);
        }).catch((err: Error) => {
            setErrMsq(err.message);
            setLoading(false);
        })
    }

    function handleSelectionChange(event: React.ChangeEvent<HTMLSelectElement>) {
        const dataId = event.target.value;
        setSelectedSessionID(parseInt(sessionId));
        onSessionChange(parseInt(sessionId));
    }

    useEffect(() => {
        fetchData();
    }, [codeType]);

    return (
        <>
            <div className="max-w-md">
                <div className="mb-2 block">
                    <Label htmlFor="sessions" value="Select session" />
                </div>
                <Select id="sessions" value={selectedRecordID} required onChange={handleDataChange}>
                    {data.map((el) => (
                        <option key={el.id} value={el.id}>{el.name}</option>
                    ))}
                </Select>
            </div>
        </>
    )
}

In the code above the key function is OnDataChange. This function is exposed outside of the component to be shared with its parent component. Means the component that will contain DropDown component.

Leave a Reply

Your email address will not be published. Required fields are marked *