Why doesn’t this select list render with the correct item selected based on the defaultValue

I have a ReactJS component:

var RegionsList = React.createClass({

    handleChange: function () {
        var regionId = this.refs.userRegions.getDOMNode().value;
        this.props.onRegionSelected(regionId);
    },

    componentDidMount: function() {
        $.get("/translation/activeuserregions", function(result) {
            if(this.isMounted()) {
                this.setState({
                    selectedRegionId: result.SelectedRegionId,
                    regions: result.Regions
                })
            }     
        }.bind(this));
    },

    getInitialState: function(props) {
        return {
            selectedRegionId: '',
            regions: []    
        }    
    },

    render: function() {
        return (
            <div id="RegionsListForm" className="navbar-form navbar-left regions-list">
                <div className="input-group navbar-searchbox">
                    <span className="input-group-addon">
                        <span>Region</span>
                    </span>
                    <select ref="userRegions" onChange={this.handleChange} defaultValue={this.state.selectedRegionId} className="form-control valid" id="region" name="region" aria-invalid="false">
                        {this.state.regions.map(function(region) {
                            return <option key={region.Id} value={region.Id} label={region.RegionName}>{region.RegionName}</option>        
                        })}                                             
                    </select>
                </div>
            </div>
        );
    },


})

It appears to work correctly. But initially it does not render with the correct item selected. Although the defaultValue appears to be set correctly so I don’t understand why.

What am I doing wrong?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

When the <select> is initially mounted, the default value is ''. Once an uncontrolled form component is in the DOM, React doesn’t look updates to the defaultValue prop. In this case it looks like your intention is to always have the selectedRegionId state match what’s shown to the user, so you may want to change defaultValue to value and add a this.setState({selectedRegionId: regionId}); call to your onChange handler; then your component state and the DOM will always be in sync.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x