Snidhi Sofpro
Snidhi Sofpro

Reputation: 499

React.js: Is there a simpler way of defining Form Input element as a best practice ? Without using another library or extension

After having gone thru a few docs & books on React, I understand that, for an Html Form input element that could be defined as:

<form>
  <label>
    Name:
    <input type="text" name="name" />
  </label>
</form>

the recommended best practice in React is to use the "Controlled component" approach with an equivalent code like the following Sample from React Forms doc:

class NameForm extends React.Component {

    constructor(props) {
      super(props);
      this.state = {value: ''};
      this.handleChange = this.handleChange.bind(this);
    } //constructor

    handleChange(event) {
        this.setState({value: event.target.value}); 
    } // handleChange

    render() {
        return (
          <form>
            <label>
              Name:
              <input 
                type="text" 
                value={this.state.value} 
                onChange={this.handleChange} 
              />
            </label>
      </form>
      );
    }  //render

} // class

Is there a simpler alternative in React itself (without adding additional libraries or extensions) ? Please excuse, if I missed something basic.

Upvotes: 0

Views: 62

Answers (1)

GeraltDieSocke
GeraltDieSocke

Reputation: 1618

That's the simplest approach. It's also correct. One way to further simplify is to give the onChange an anonymous arrow function.

  <form>
        <label>
          Name:
          <input 
            type="text" 
            value={this.state.value} 
            onChange={e => this.setState({ value: e.target.value })} 
          />
        </label>
  </form>

But no advantage here really. Your approach makes it more readable.

But there is a more simple way to initialize state.

It's like this:

class NameForm extends React.Component {

    state = { value: "" }
    ....
}

And if you make class methods arrow functions you don't have to bind them:

handleChange = (event) => { .... }

Upvotes: 3

Related Questions