javascriptreactjsreact-select

ReactJs select, no value displayed


I'm learing reactJs and trying to use react-select.

html:

<div class="col-md-2">
            <div class="well">
                <h1>h1</h1>
                <div id="countriesSelect"></div>
                <div id="exp"></div>
                <!-- Scripts -->
                <script src="/js/bundle.js"></script>
            </div>
</div>

app.js:

var React = require('react');
var ReactDOM = require('react-dom');
var Select = require('react-select');

const getOptions = (input) => {
    return fetch('//api.local/api/countries') //users/${input}.json
        .then((response) => {
            return response.json();
        }).then((json) => {

            var data = [];
            json['data'].forEach(function(item) {
                data.push({value:item.attributes.slug,label:item.attributes.title})
            });
            return { options: data };
        });
}

ReactDOM.render(
    <Select.Async
        name="countries"
        loadOptions={getOptions}
    />,
    document.getElementById('countriesSelect')
);


var options = [
    { value: 'one', label: 'One' },
    { value: 'two', label: 'Two' }
];

ReactDOM.render(
    <Select
        name="form-field-name"
        label
        options={options}
    />,
    document.getElementById('exp')
);

app.js to bundle.js -> browserify -t [ babelify ] public/js/app.js -o public/js/bundle.js

Result:

enter image description here

The problem - when trying to select someting from dropdown, no value shown in select. Always see the Select... label.


Solution

  • it looks like you are missing the value prop on the Select component and need an onChange prop as well to handle when you click a dropdown option. I highly suggest making your own select component that wraps the react-select library that way you can pass custom props and create custom functions that are used with the react-select library.

    var value; // initialize the value variable
    
    function updateValue(selectVal) {
        value = selectVal; // update value variable to new value
    }
    
    <Select 
        name="form-field-name"
        label
        value={value} // set value to value
        onChange={updateValue}
        options={options}
    />
    

    that should get you where you need to be.