1

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 Answer 1

1

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.

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

2 Comments

I have added an id attribute, just like you mentioned and also changed the code. But in my select box I still get: 2017-05-03,2018-02-01 (as one option), instead of getting listed by order like: option 1->2017-05-03 option 2->2018-02-01.
I think the culprit is the item.dates which might be an array. I've updated my answer but if it still doesn't work, please update your question by including the JSON file you are reading.

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.