I can't seem to get a select element to have options based on elements of an array in state. I've tried a bunch of different methods, but this seemed to be the most granular (I'm just getting back into react after a few years, and am trying to relearn it).
I have a whole stateful component for the dropdown, shown below:
import React, { Component } from "react";
import "./Dropdown.css";
class Dropdown extends Component {
constructor(props) {
super(props);
this.state = {
options: [],
selectedOption: "",
};
};
componentDidMount = () => {
this.setState({
options: this.props.options
});
};
displayOptions = () => {
this.state.options.map(item => {
return <option value={item} id="1">{item}</option>
});
};
render() {
return(
<select className="dropdown">
{ this.displayOptions() }
</select>
)
};
};
export default Dropdown;
The props that are being pulled in are structured as an array of either strings or numbers. As an example:
[2020,2019,2018,2017,2016,2015,2014,2013,2012,2011,2010,2009,2008,2007,2006,2005,2004,2003,2002,2001,2000,1999,1998,1997,1996,1995,1994,1993,1992]
Looking at my React dev tools, state is getting correctly populated with the array. And according to my understanding of React, once state is populated, the component should rerender, calling displayOptions, mapping through the array, and filling the select element with option elements.
But when I go to the actual page, no matter how long I wait or what I do, the dropdown never opens to show options. I guess I can't tell if I just have a typo that's keeping this from working properly, or if I'm missing a larger rule of either React, array prototypes, or something else entirely.
Any help would be greatly appreciated. And please let me know if more information is needed. I feel like I've provided all relevant info, but I'm happy to provide more if needed.
return from the function
displayOptions = () => {
return this.state.options.map(item => {
return <option value={item} id="1">{item}</option>
});
};
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments