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.