Mitch
Mitch

Reputation: 193

Populating new select options from data returned from previous select using React

With React, render and populate new select upon onChange from the first.

I have successfully fetched the data upon onChange from the first select dropdown. Now how to get the updated state rendered on the same page.

constructor(props){
super(props);
this.state = {
partitions: [] 
}

handleSubmit(event) {
    const pk = event.target.value;
    fetch(`api/locations/${pk}`)
        .then(response => response.json())
        .then(body => this.setState({partitions: body}))
}
render() {
    return (
        <div>
            <div className={"form-group"}>
                <label>Locations</label>
                <select className={"form-control"}
                        name={"location"} value={"location"}
                        onChange={this.handleSubmit}>
                    <option value={""} key={""}>---------</option>
                    {Object.entries(this.props.data)
                       .map(location=>
                        <option value={location[1].id} 
                             key={key(location)}>
                            {location[1].location}
                        </option>
                    )}
                </select>
            </div>

How do I get that data to render underneath the first select dropdown?

Upvotes: 0

Views: 158

Answers (1)

Neil
Neil

Reputation: 968

All you need to do is create another select and wrap It around a condition which checks of the length is more than 0.

const { partitions } = this.state;
const displayPartitions = partitions.length > 0;

<>
  // Previous <select/>

  {displayPartitions && (
    <select>
      {partitions.map(item => (
        ...
      ))}
    </select>
  )}
</>

Personally I would have a component that handles the select, you could use it twice on a page and populate once with this.props.data then secondly with this.state.partitions.

If I read your response correctly when you make your selection you already have data so you just need to compose another select element.

Upvotes: 1

Related Questions