A cascading dropdown list in an SPFx web part using PnP JS can be created by following these steps:
Install the PnP JS library by running the command npm install
@pnp/pnpjs in the terminal.
Import the necessary modules from the PnP JS library in your web
part's component class.
In the componentDidMount() method, use PnP JS to retrieve the options
for the first dropdown list from a SharePoint list.
Bind the options to the state variable of the first dropdown list.
Create a method to handle the onChange event of the first dropdown
list. In this method, use PnP JS to retrieve the options for the
second dropdown list based on the selected option of the first
dropdown list.
Bind the options to the state variable of the second dropdown list.
In the render method, use the state variables to set the selected
options of the two dropdown lists and to populate the options.
Use the onChange event of the first dropdown list to trigger the
method that retrieves the options for the second dropdown list and
updates the state.
Here is an example of how you might retrieve options for the first dropdown list using PnP JS:
import { sp } from "@pnp/sp";
componentDidMount() {
sp.web.lists.getByTitle("ListName").items.select("Title").get().then((items: any[]) => {
this.setState({
firstDropdownOptions: items.map(i => ({ key: i.Title, text: i.Title }))
});
});
}
handleFirstDropdownChange = (event: any) => {
const selectedOption = event.target.value;
sp.web.lists.getByTitle("ListName").items.filter(`ColumnName eq '${selectedOption}'`).select("Title").get().then((items: any[]) => {
this.setState({
secondDropdownOptions: items.map(i => ({ key: i.Title, text: i.Title }))
});
});
}