3

Here is my simple select menu component.

Question is: how to set first item.id (from json response) as default value for generated select-menu?

Code:

import React from 'react'
import axios from 'axios'

const Handler = React.createClass({

    loadFromServer : function() {
        axios({
            method: 'get',
            url: '/api_url'
        })
        .then(function(response) {
            this.setState({data: response.data});
        }.bind(this))
        .catch(function(response) {
            this.setState({error: true})
        }.bind(this));
    },

    getInitialState() {
        return {
            data: []
        }
    },

    componentDidMount: function() {
        this.loadFromServer();
      },

  render() {
    var {data} = this.state;
    return (
        <select ref="select" id="select">
            {data.map((item, i) => {
                return <option value={item.id} key={i}>{item.name}</option>
            })}
        </select>
    )
  }
});

export default Handler

JSON:

[{id: 'item_id', name: 'item_name'},{id: 'item_id_2', name: 'item_name_2'}]
Toon
  • 652
  • 1
  • 11
  • 24

1 Answers1

0

You can set value attribute on select tag (in your case the value of this attribute should be set to id of the first item):

 <select ref="select" id="select" value="data[0].id">
            {data.map((item, i) => {
                return <option value={item.id} key={i}>{item.name}</option>
            })}
  </select>

You can check React docs for more details.

Bartek Fryzowicz
  • 6,464
  • 18
  • 27