Implement Primereact Cascade Drop-down In React-JS

Hello Developers, In this blog we are going to learn how we can implement cascade dropdown in React-JS

CascadeSelect is one type of component to select a value from a nested structure of options.

First, create a new app using the following command

npx create-react-app

Then install these packages in your app:

npm i primereact primeflex primeicons

Then import these all files in your component

import "primereact/resources/themes/lara-light-indigo/theme.css";
import "primereact/resources/primereact.min.css";
import "primeicons/primeicons.css";

Now import cascade select menu from primereact

import { CascadeSelect } from 'primereact/cascadeselect';

Now make an array of an object

For Example here, I created an array of an object which is containing the name of the country, code, and array of states and in the array of states we have the name of the state and array of cities of that particular state

Like this:-

const countries = [
        {
            name: 'India',
            code: 'IN',
            states: [
                {
                    name: 'Gujarat',
                    cities: [
                        { cname: 'Surat' },
                        { cname: 'Bharuch' },
                        { cname: 'Anand' }
                    ]
                },
                {
                    name: 'Delhi',
                    cities: [
                        { cname: 'North-East' },
                        { cname: 'North-West' }
                    ]
                },
            ]
        }
    ]

Now we are going to use this country array to display the cascade dropdown

Like this:-

<div style={{ height: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
      <CascadeSelect
          value={selectedCity}
          options={countries}
          optionLabel={"cname"}
          optionGroupLabel={"name"}
          optionGroupChildren={['states', 'cities']}
          style={{ minWidth: '14rem' }}
          placeholder={"Select a City"}
          onChange={event => setSelectedCity(event.value)} />
</div>

Demo:-

Submit a Comment

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

Subscribe

Select Categories