How to map an array of strings from react state to a select box

Viewed 646

I read a json file in the first select box and set the value as state and i don't know how to read that value to another select box. All I get is the whole array as one string.

This is the code where i set state as an object from the first select box:

constructor(props) {
    super(props);
    this.state = {
        selectedCourse: {}
        
    };
    this.onSelectCourse = this.onSelectCourse.bind(this);
}
onSelectCourse(e) {
    console.log(e.target);
    this.setState(
        {
            selectedCourse: {
                ...this.state.selectedCourse,
                [e.target.id]: [e.target.value]
            }
        },
        () => {
            console.log(this.state);
        }
    );
}

render() {
    const { selectedCourse } = this.state;

This is the first select box:

<select onChange={this.onSelectCourse}>{CoursesList.courses.map((item, i) =><option key={i} value={item.dates}>{item.name}</option>)}</select>

This is the select box where i want to display the data from state object array:

<select>{Object.entries(this.state.selectedCourse).map((item) =><option key={item}>{item}</option>)}</select>
1 Answers

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value]

Meaning each item in the .map function is an array such as [key, value].

What I think you want to do is,

<select>
{Object.entries(this.state.selectedCourse)
  .map(
   ([key, value]) => (<option key={key} value={value}>{value}</option>)
  )
}
</select>

If you just want the object values and not the keys, you can use Object.values() or for inverse Object.keys().


Also, in your setState you are accessing [e.target.id] but your <option> tag has no id attribute set.


EDIT:

As pointed out by OP,

But in my select box I still get: 2017-05-03,2018-02-01 (as one option)

I think that could be because of the item.dates in first select field (<option key={i} value={item.dates}>{item.name}</option>). Is the item.dates an array ? I recommend you check your JSON.

Related