Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Just learning React and I have seen various different ways to get a value from a text input. I wanted ask whether all of them are correct or if there are any advantages to using one over another.

Method 1):

MyForm = React.createClass({
    getInitialState: function() {
        return {
            username: ""
        };
    },
    onSubmit: function(e) {
        e.preventDefault();
        this.setState({
            username: this.refs.username.getDOMNode().value
        });
        /* Do something... */
    },
    render: function(){
        return (
            <div>
                <form onSubmit={this.onSubmit} id="login-form">
                    <input type="text" ref="username"></input>
                </form>
            </div>
        )
    }
});

Method 2):

MyForm = React.createClass({
    getInitialState: function() {
        return {
            username: ""
        };
    },
    handleUsernameChange: function(evt) {
        this.setState({
            username: evt.target.value
        });
    },
    onSubmit: function(e) {
        e.preventDefault();
        /* Do something... */
    },
    render: function(){
        return (
            <div>
                <form onSubmit={this.onSubmit} id="login-form">
                    <input type="text" onChange={this.handleUsernameChange}></input>
                </form>
            </div>
        )
    }
});
share|improve this question
    
both are ok, I use the 2nd option. With react you don't need the forms as the are. You can have an input, then set the state with the user input, and with whatever element you want onclick event, take the components state, and make an ajax request with the user input. – jgldev Apr 3 '16 at 19:09
    
Thanks for the comment. So, if you had a large form of say 100 elements (and you wanted to monitor their state), you would create 100 different 'handleChange' functions? – JoeTidee Apr 3 '16 at 19:31
    
well that would depend on if there are 100 different actions that effect those elements, you should keep them all in state, and abstract away as much as possible. That said, the whole point of react is small components, so if you're doing that...well, its not good. – JordanHendrix Apr 3 '16 at 20:08
    
Lets say there are five elements in this component, it seems arduous to have to right five functions to handle each change and save the state. Could there simply not be a generic funtion that monitors changes and saves the state in an object/array? – JoeTidee Apr 3 '16 at 22:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.