user788448
user788448

Reputation: 797

React-select dropdown does not render data

I am trying to use react-select for a dropdown. The console.log shows my subjectList array as [object object],[object,object]... If I don't use react-select, my dropdown renders fine. I have no clue what the problem is. Below is my code:

import React, {Component} from 'react';
import axios from 'axios';
import Select from 'react-select';


class Subject extends Component{
    state={subjectList:[]};
    componentDidMount(){
        this.getSubjects();
    }
   //get distinct subject
   getSubjects= ()=>{

    axios.get('/apiURL')
    .then(response=>{

        const subjects= response.data;
       //remove duplicates
        const subjectList = [...new Map(subjects.map(item => [item["SUBJECT"], item])).values()];

        this.setState({subjectList: subjectList});


      });  

    };

    render(){

    let subjectList=this.state.subjectList.map((item,i) => <option key={i} value={item.SUBJECT}>{item.CATEGORY}</option>);

        return(
            <Select  options={subjectList} />
        );
    }

 }


  export default Subject;

If I change return to the below code and it works fine. But I want to try react-select for my dropdown.

return (
    <div>
    <select>
        <option value=''>Select a subject</option>

        {this.state.subjectList.map((item,indx)=><option key={indx} value={item.SUBJECT}>{item.CATEGORY}</option>)}

    </select>

    </div>
);

Upvotes: 0

Views: 2277

Answers (2)

Maria Odintsova
Maria Odintsova

Reputation: 647

you can use for refresh

_defer(() => $(this.selectRef).selectpicker('refresh'));

Upvotes: 1

azundo
azundo

Reputation: 6052

Read the usage section from the react-select docs: https://github.com/JedWatson/react-select#installation-and-usage

In your case subjectList in render should be an array of objects with 'value' and 'label' keys, not <option> elements. So something like:

let subjectList = this.state.subjectList.map(item => ({value: item.SUBJECT, label: item.CATEGORY}));

Upvotes: 2

Related Questions