1

I want to add two dropdowns.

  1. Genre
  2. Books

The Books dropdown would be dependent on value selected in Genre dropdown. I am using react-select library. With my failed efforts I was able to do this. Dependent dropdown does get filtered, but no value is selected in the select bar. This is my code.

import React, { Component } from "react";
import Select from "react-select";

class Condiontaldropdown extends Component {
  constructor() {
    super();
    this.state = {
      selectedOption: {},
      selectedOption2: {},
    };
  }

  handleChange1 = (selectedOption) => {
    this.setState({ selectedOption });
  };

  handleChange2 = (selectedOption) => {
    this.setState({ selectedOption2: selectedOption });
  };

  render() {
    const Genres = [
      { value: "Fiction", label: "Fiction" },
      { value: "Murder", label: "Murder" },
      { value: "Thriller", label: "Thriller" },
    ];

    const Books = [
      { value: "GOT", label: "GOT", link: "Fiction" },
      { value: "LOTR", label: "LOTR", link: "Fiction" },
      { value: "Angel And Demons", label: "Angel And Demons", link: "Murder" },
      { value: "Dragon", label: "Dragon", link: "Thriller" },
      { value: "Tattoo", label: "Tattoo", link: "Thriller" },
    ];

    const filteredOptions = Books.filter(
      (o) => o.link === this.state.selectedOption.value
    );
    return (
      <div>
        <p> Select your favourite Genre</p>
        <Select
          value={this.state.selectedOption.value}
          onChange={this.handleChange1}
          options={Genres}
        ></Select>
        <p>Select your favourite Book from that genre</p>
        <Select
          value={this.state.selectedOption2.value}
          onChange={this.handleChange2}
          options={filteredOptions}
        ></Select>
      </div>
    );
  }
}

export default Condiontaldropdown;

1 Answer 1

2

You are passing .value to the value props of Select but it is not correct. Please check the following code.

 return (
      <div>
        <p> Select your favourite Genre</p>
        <Select
          value={this.state.selectedOption}
          onChange={this.handleChange1}
          options={Genres}
        ></Select>
        <p>Select your favourite Book from that genre</p>
        <Select
          value={this.state.selectedOption2}
          onChange={this.handleChange2}
          options={filteredOptions}
        ></Select>
      </div>
    );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.