I
I
Isaac Clark2015-11-21 14:16:08
JavaScript
Isaac Clark, 2015-11-21 14:16:08

How to correctly hang onChange on input in React.js?

Hello.
There are two buttons. Depending on which button I clicked, text fields with data are rendered.

var Data = [1, 2, 3];

var Test = ['Vasya', 'Kate', 'TEst'];

var Main = React.createClass({

    getInitialState: function () {
        return {
            inputs: null
        }
    },

    _getData: function () {
        this.setState({
            inputs: Data
        });
    },

    _getTest: function () {
        this.setState({
            inputs: Test
        });
    },

    createBtnData: function () {
        return <button onClick={this._getData}>Get Data</button>;
    },

    createBtnTest: function () {
        return <button onClick={this._getTest}>Get Test</button>;
    },

    _changeValue: function (e) {
        var val = e.target.value;

        this.setState({
            inputs: val
        });
    },

    createInput: function () {

        if (this.state.inputs) {
            return this.state.inputs.map(function (item, i) {
                return <input key={i} value={item} onChange={this._changeValue} />
            }.bind(this));
        }
    },

    render: function() {
        return <div>
                   {this.createBtnData()}
                   {this.createBtnTest()}
                   {this.createInput()}
               </div>;
    }
});

The problem is that when I click on one of the fields and try to enter text, the following error is thrown:
TypeError: this.state.inputs.map is not a function
I understand that the problem is that the map method is trying to be called again for the data that I enter, and since it is no longer an array, but a string, then hence the error.
Question: in this case, how can I correctly hang the onChange handler on the input so that the code works correctly, that is: render the necessary data, make changes to them, if necessary, render others.
Thanks for the help.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir Rodkin, 2015-11-21
@Dark_Knight

For example, this is jsfiddle.net/VovanR/0btxjm5c We
replace the value of the element by index and update the state.
Perhaps there is another way.

M
mass3ff3ct, 2015-12-01
@mass3ff3ct

You have an error in your code. Initially, the inputs state variable is an array. But in the onChange event handler, you are assigning a string to inputs. The string does not have a map method which is used in createInput

M
Maxim, 2016-03-12
@maxfarseer

Described working with input as a controlled and uncontrolled component here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question