1

I am trying to select multiple value from from select field, but I can only select one field and I fetch data from API and in API endpoint I can select multiple user like user=1,2,3 and I also want to select multiple user in react js. Here is my code:

This is my form:

 <select
      multiple={true}
      onChange={this.handleChange}
      value={this.state.selectedOptions}
      className="form-control btn-block"
      id="exampleFormControlSelect2 btn-block"
      style={{
        width: "200px",
        color: "rgba(19, 183, 96, 1.0)"
      }}
      name="idd"
    >
      {this.state.movies.map(c => (
        <option value={c.pk}>{c.user1}</option>
      ))}
    </select>

Here is handle change event and fetch data:

handleChange(event) {
    //this.setState({value: event.option});
    this.setState({
      value: Array.from(event.target.selectedOptions, item => item.value)
    });
  }

  // Get Data From Backend
  async componentDidMount() {
    try {
      const res = await fetch(config.apiUrl.reportModel);
      const movies = await res.json();
      // console.log(report);
      this.setState({
        movies
      });
    } catch (e) {
      console.log(e);
    }
  }

Please help. I'm stuck here and I don't know how to resolve this.

2 Answers 2

2

in your select field props change value={this.state.selectedOptions} to value={this.state.value}

working (simplified) snippet

class SomeComponent extends React.Component{
    state={
        value:null,
        movies:[{user1:'iRobot', pk:'1'},{user1:'Matrix', pk:'2'},{user1:'Hackers' , pk:'3'}]
    }

    handleChange(event) {
        this.setState({
             value : Array.from(event.target.selectedOptions, item => item.value)
        });
    }
    
    
    render(){
    return (
        <select
            multiple
            onChange={(e)=>console.log()}
            value={this.state.value}
        >
            {this.state.movies.map(movie => (
                <option value={movie.pk}>{movie.user1}</option>
            ))}
        </select>
    )
    }

}

ReactDOM.render(
    <SomeComponent />,
    document.getElementById("react")
);
<div id='react'></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

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

Comments

0

There is a library react-select which you can use to achieve the desired functionality. Following is the link to official npm site for that package

https://www.npmjs.com/package/react-select

Comments

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.