Benjamin Li
Benjamin Li

Reputation: 1697

In Redux, how to get user input

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

Upvotes: 2

Views: 110

Answers (2)

Prasanna Mahendiran
Prasanna Mahendiran

Reputation: 506

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.

Upvotes: 0

Chris
Chris

Reputation: 58312

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>

Upvotes: 1

Related Questions