Category Subcategory Dropdown in React js

Category Subcategory Dropdown in React js

In web development, dropdowns are commonly used UI components to make it easier for users to select from a list of options. However, what if you have a large number of options to display? This is where category subcategory dependent dropdowns come in handy. These dropdowns allow users to select a category and then display only the relevant subcategories for that category.

In this tutorial, you will learn how to implement category subcategory dependent dropdowns in React.

How to Create Dependent Category Subcategory Dropdown in React js

By using category subcategory dependent dropdowns, you can make it easier for users to select from a large number of options and improve the overall user experience.

  • Step 1: Create the Category Dropdown Component
  • Step 2: Create the Subcategory Dropdown Component
  • Step 3: Create the Parent Component

Step 1: Create the Category Dropdown Component

The first step is to create the category dropdown component. This component will contain the list of categories that the user can choose from. Here’s an example code snippet for the category dropdown component:

import React, { useState } from 'react';

const CategoryDropdown = (props) => {
  const [selectedCategory, setSelectedCategory] = useState("");

  const handleCategoryChange = (event) => {
    setSelectedCategory(event.target.value);
    props.onCategoryChange(event.target.value);
  };

  return (
    <div>
      <label htmlFor="category">Select a category:</label>
      <select id="category" value={selectedCategory} onChange={handleCategoryChange}>
        <option value="">-- Select a category --</option>
        <option value="category1">Category 1</option>
        <option value="category2">Category 2</option>
        <option value="category3">Category 3</option>
      </select>
    </div>
  );
};

export default CategoryDropdown;

In this component, you use the useState hook to keep track of the selected category. When the user selects a category, and update the state using the setSelectedCategory function. And also pass the selected category value to the parent component using the props.onCategoryChange callback function.

Step 2: Create the Subcategory Dropdown Component

Next, you need to create the subcategory dropdown component. This component will contain the list of subcategories based on the selected category. Here’s an example code snippet for the subcategory dropdown component:

import React, { useState, useEffect } from 'react';

const SubcategoryDropdown = (props) => {
  const [selectedSubcategory, setSelectedSubcategory] = useState("");
  const [subcategories, setSubcategories] = useState([]);

  useEffect(() => {
    // simulate an API call to get subcategories based on the selected category
    const getSubcategories = async () => {
      const subcategories = await fetch(`/api/subcategories?category=${props.category}`)
        .then((response) => response.json());
      setSubcategories(subcategories);
    };
    getSubcategories();
  }, [props.category]);

  const handleSubcategoryChange = (event) => {
    setSelectedSubcategory(event.target.value);
    props.onSubcategoryChange(event.target.value);
  };

  return (
    <div>
      <label htmlFor="subcategory">Select a subcategory:</label>
      <select id="subcategory" value={selectedSubcategory} onChange={handleSubcategoryChange}>
        <option value="">-- Select a subcategory --</option>
        {subcategories.map((subcategory) => (
          <option key={subcategory.id} value={subcategory.id}>
            {subcategory.name}
          </option>
        ))}
      </select>
    </div>
  );
};

export default SubcategoryDropdown;

In this component, you use the useState hook to keep track of the selected subcategory and the list of subcategories. And also use the useEffect hook to simulate an API call to get the subcategories based on the selected category. When the user selects a subcategory, and update the state using the setSelectedSubcategory function and pass the selected subcategory value to the parent component using the props.onSubcategoryChange callback function.

Step 3: Create the Parent Component

Finally, you need to create the parent component that will contain both the category and subcategory dropdown components. Here’s an example code snippet for the parent component:

import React, { useState } from 'react';
import CategoryDropdown from './CategoryDropdown';
import SubcategoryDropdown from './SubcategoryDropdown';

const CategorySubcategoryDropdown = () => {
  const [selectedCategory, setSelectedCategory] = useState("");
  const [selectedSubcategory, setSelectedSubcategory] = useState("");

  const handleCategoryChange = (category) => {
    setSelectedCategory(category);
    setSelectedSubcategory("");
  };

  const handleSubcategoryChange = (subcategory) => {
    setSelectedSubcategory(subcategory);
  };

  return (
    <div>
      <CategoryDropdown onCategoryChange={handleCategoryChange} />
      {selectedCategory && (
        <SubcategoryDropdown
          category={selectedCategory}
          onSubcategoryChange={handleSubcategoryChange}
        />
      )}
      {selectedSubcategory && (
        <p>You have selected subcategory {selectedSubcategory}.</p>
      )}
    </div>
  );
};

export default CategorySubcategoryDropdown;

In this component, you use the useState hook to keep track of the selected category and subcategory. and also define callback functions to update the state when the user selects a category or subcategory. Finally, render the category and subcategory dropdown components, and display the selected subcategory value.

Conclusion

In this tutorial, you have explored how to implement category subcategory dependent dropdowns in React. you created a category dropdown component to display the list of categories, a subcategory dropdown component to display the list of subcategories based on the selected category, and a parent component to contain both the category and subcategory dropdown components. By using category subcategory dependent dropdowns, you can make it easier for users to select from a large number of options and improve the overall user experience.

Recommended React JS Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

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