React-select: How to get current value?

Created on 13 May 2015  路  14Comments  路  Source: JedWatson/react-select

For example I have a form with few select items. I would like to validate this form when user submits the form. So, I would like to have a getValue method the select component to use it like below:

var Form = React.createClass({
    render: function () {
        return (
            <form onSubmit={this.submit}>
                <Select ref="one" ... />
                <Select ref="two" ... />
                <Select ref="three" ... />
                ...
                <button type="submit">Submit</button>
            </form>
        );
    },
    submit: function () {
        if (this.validate()) {
            // send form to the server
        } else {
            // show errors
        }
    },
    validate: function () {
        var isValid = true;
        for (key in this.refs) {
            var component = this.refs[key];
            var value = component.getValue ? component.getValue() : component.getDOMNode.value;
            // validation ...
        });
        return isValid;
    }
})

At the moment I see only one way to do this using onChange for each component and store the values in some place. But I think, with getValue method it will be more clear and simple.

categorquestion

Most helpful comment

Is there a way to get current value if the onChange event is not fired?

All 14 comments

+1. For anyone with a similar issue - another approach can be to use the asyncOptions which allows you to get the current value as input, and then just use your original options in the callback, if they don't need to change (as was my case):


  doStuffWithInput(input) {
    // do some stuff
  }

  getOptions(input, callback) {
    let options = { options: this.props.modules } // I just used my original props
    doStuffWithInput(input)
    callback(null, options)
  }

  render() {

    return (
        <SelectContainer inputChange={this.inputChange}>
          <Select
            name="MySelect"
            value="ABC"
            asyncOptions={this.getOptions}
            autoload={false}
          />
        </SelectContainer>
    );
  }
}

The Usage documentation shows that you can use the onChange prop on the Select component directly.

I think that the README answers this question and that this issue can now be closed.

Is there a way to get current value if the onChange event is not fired?

Storing the value with the onChange probably makes sense for some situations, but I found it to be unnecessarily cumbersome. Also noted in the Usage documentation is that there's a hidden input field that stores the value of the select box, named with the name you pass in to Select. For the OP's question, he could get the value with:
$('input[name='+key+']').val();
That's assuming he's using jQuery and the Select was created as:
<Select ref="one" name="one" ... />
Not as elegant as a getValue, but at least it's succinct.

This is a very hacky way to do this but until a getValue() method is added this (pseudo code) should work:

React.createClass({

  getInitialState() {
    return {
      email: null,
    }
  },

  _handleSubmit(e) {
    e.preventDefault()
    const email = this.refs.email.state.inputValue
    // now do something with email...
  },

  render() {
    const options = { /* your options */ }
    return (
      <form onSubmit={this._handleSubmit}>
        <Select
          options={options}
          ref='email'
          value={this.state.email}
        />
      </form>
    )
  },
})

Any progress on this one? Thanks!

I still didn't undertood the need of getValue method when we already have onChange handler (that gives us the select value) which could be saved in parent component state.
So upon form submission, saved state value could be validated.
I feel this is the basic thought process for react components (and also use of ref should be highly avoided)

Ok thanks @aqumus

Based on the earlier replies by @radar and @danawoodman, I took this route in the meantime. I didn't find it too cumbersome, but I'm fairly new at the whole JS world (started developing a web-app to manage biology-related data).
However, as @benrolsen pointed out, the documentation mentions a "hidden input field", which sounds perfect. However, I cannot find how to access (his code snippet is too abstract for me).

@kevinrue, @benrolsen code snippet simply does is:

  • Assigns name props to React-Select component

  • then access/get the hidden input field using jquery selector where the selector is
    $( "input[name='name_prop_value_givenToReactSelect']" ).val()
    which returns the hidden input field value

<Select name="anyCustomName"/>
var hiddenInputValue = $( "input[name='anyCustomName']" ).val();

Consider this scenario.

I have a multi select dropdown. One default value is selected, and when I select one more option I only get the last one in the onchange event. Does seem like default values are stored..

I'm wondering a way to do this as well. I have three dropdowns that filter the list of items depending on what the user selects in the prior dropdown. Could onChange be used in this circumstance or is it a limitation of react-select itself? Using the inspector, I see a buried input within the div's but the value attribute remains unset when I select/change a new item.

+1

@dhniels you can access all selected values by doing querySelectorAll and reference those inputs. Each option selected has an input in itself.

So

const nodeList = formRef.querySelectorAll('input[name="reactSelectName"]')
// gives you all selected options from react-select

Then you can iterate thorugh the nodeList, get values, update options based on those values, etc...

Version 1 of react-select is no longer supported.

In the best interest of the community we've decided to spend the time we have available on the latest version.

We apologise for any inconvenience.

Please see:

  1. v1 to v2 upgrade guide
  2. v1 documentation and examples
Was this page helpful?
0 / 5 - 0 ratings

Related issues

geraldfullam picture geraldfullam  路  3Comments

AchinthaReemal picture AchinthaReemal  路  3Comments

juliensnz picture juliensnz  路  3Comments

mjuopperi picture mjuopperi  路  3Comments

MindRave picture MindRave  路  3Comments