2

I am new to reactjs I am trying to learn React-js. I want to build dependent dropdown Menu. Where if I select Genre fiction it should display books in fiction genre. All this is hardcoded for now I haven't linked it to the database/backend.

I searched few things and came up with this but its not working properly.

class Dropdown extends Component {
  constructor(props) {
    super(props);
    this.state = {
      Genres: [],
      Books: [],
      selectedGenre: "--Choose Genre--",
      selectedBook: "--Choose Book--",
    };

    this.ChangeGenre = this.ChangeGenre.bind(this);
    this.ChangeBook = this.ChangeBook.bind(this);
  }

  componentDidMount() {
    this.setState({
      Genres: [
        { name: "Fiction", Books: ["GOT", "LOTR", "Harry Potter"] },
        { name: "Murder", Books: ["Dragon", "Tattoo", "Girl"] },
        { name: "Thriller", Books: ["Angel", "Lost Symbol", "Davinci"] },
      ],
    });
  }

  ChangeGenre(event) {
    this.setState({
      selectedGenre: event.target.value,
    });
    this.setState({
      Books: this.state.Genres.find((b) => b.name === event.target.value).Books,
    });
  }

  ChangeBook(e) {
    this.setState({ selectedBook: e.target.value });
    const stats = this.state.Genres.find(
      (g) => g.name === this.state.selectedGenre
    ).Books;
    this.setState({
      Books: stats.find((stat) => stat === e.target.value).Books,
    });
  }

  render() {
    return (
      <div id="container">
        <h2>Cascading or Dependent Dropdown using React</h2>

        <div>
          <label>Genre</label>
          <select
            placeholder="Genre"
            value={this.state.selectedGenre}
            onChange={this.ChangeGenre}
          >
            <option>--Choose Genre--</option>
            {this.state.Genres.map((e, key) => {
              return <option key={key}>{e.name}</option>;
            })}
          </select>
        </div>

        <div>
          <label>Books</label>
          <select
            placeholder="Books"
            value={this.state.selectedBook}
            onChange={this.ChangeBook}
          >
            <option>--Choose Book--</option>
            {this.state.Books.map((e, key) => {
              return <option key={key}>{e.name}</option>;
            })}
          </select>
        </div>
      </div>
    );
  }
}

The Books Dropdown doesn't show any books and on clicking any option throws an error cannot read 'Books' of Undefined.

2 Answers 2

1

import React, { Component } from "react";

class Dropdown extends Component {
  constructor(props) {
    super(props);
    this.state = {
      Genres: [],
      Books: [],
      selectedGenre: '--Choose Genre--',
      selectedBook: '--Choose Book--'
    };

    this.ChangeGenre = this.ChangeGenre.bind(this);
    this.ChangeBook = this.ChangeBook.bind(this);
  }

  componentDidMount() {
    this.setState({
      Genres: [
        { name: "Fiction", Books: ["GOT", "LOTR", "Harry Potter"] },
        { name: "Murder", Books: ["Dragon", "Tattoo", "Girl"] },
        { name: "Thriller", Books: ["Angel", "Lost Symbol", "Davinci"] }
      ]
    });
  }

  ChangeGenre(e) {
    e.preventDefault();
    const Books = this.state.Genres.find(
      (genre) => genre.name === e.target.value
    ).Books;
    this.setState({ selectedGenre: e.target.value, Books });
  }

  ChangeBook(e) {
    e.preventDefault();
    this.setState({ selectedBook: e.target.value });
  }

  render() {
    return (
      <div id="container">
        <h2>Cascading or Dependent Dropdown using React</h2>

        <div>
          <label>Genre</label>
          <select
            placeholder="Genre"
            value={this.state.selectedGenre}
            onChange={this.ChangeGenre}
          >
            <option>--Choose Genre--</option>
            {this.state.Genres.map((genre, key) => {
              return <option key={key}>{genre.name}</option>;
            })}
          </select>
        </div>

        <div>
          <label>Books</label>
          <select
            placeholder="Books"
            value={this.state.selectedBook}
            onChange={this.ChangeBook}
            disabled={this.state.selectedGenre === '--Choose Genre--'}
          >
            <option>--Choose Book--</option>
            {this.state.Books.map((book, key) => {
              return <option key={key}>{book}</option>;
            })}
          </select>
        </div>
      </div>
    );
  }
}

export default Dropdown;

Sign up to request clarification or add additional context in comments.

Comments

0

If it is not to late, you can also try React Conditional Selection approach.

1 Comment

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

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.