In Redux, how to get user input

Question

I have a form, how to get the use input in the handleSubmit() method?

handleSubmit(e) {
    e.preventDefault()
    //how to get the user input?
}

render() {
    return (
        <div className="col-sm-4">
            <form onSubmit={this.handleSubmit}>
                <input type="text" placeholder="user"/>
                <input type="text" placeholder="comments"/>
                <input type="submit" hidden/>
            </form>
        </div>
        )
    }

so far, I know three solutions: The first one, use refs, but I can see there are lots of people saying that we should avoid using it

The second one, add onChange() to each <input>, e.g.

class Example extends React.Component {

    state = {
      inputValue: ""
    };

    handleInputChanged(e) {
      this.setState({
        inputValue: e.target.value
      });
    }

    render() {
        return ( 
          <div>
            <input onChange={this.handleInputChanged.bind(this)} value={this.state.inputValue}>
            </div>
      );
  }
}

this one is fine with a few inputs. But if the form has 20 input fields, then there are 20 different onChange methods?

third, use some npm module, like redux-form.

any other suggestion? Thanks


Show source
| reactjs   | forms   | redux   2017-01-06 12:01 2 Answers

Answers ( 2 )

  1. 2017-01-06 12:01

    You can actually just do an onChange on the parent form like so:

    onChange(e) {
        switch(e.target.type) {
            case 'checkbox':
                this.setState({ [e.target.name]: e.target.checked });
                break;
            default:
                this.setState({ [e.target.name]: e.target.value });
                break;
        }
    }
    
    // in render
    <form onChange={this.onChange.bind(this)}>
        <input name="foo1" />
        <input name="foo2" />
        <input name="foo3" />
        <input name="foo4" />
        <input name="foo5" />
        <input name="foo6" />
        <input name="foo7" />
        <input name="foo8" />
    </form>
    
  2. 2017-01-06 12:01

    There are certain libraries like https://github.com/christianalfoni/formsy-react, https://github.com/prometheusresearch/react-forms. These forms have additional functions pre written for form submitting, validations. I think using refs is a tedious and unwanted task if the form is big with the reason being that if it is controlled form you need to access the state value for controlled components which brings unnecessary complications. You can do it but it is better to use prewritten libraries.

◀ Go back