Forms in React

From Logic Wiki
Jump to: navigation, search


Simple form

preventDefault

To prevent default submit behaviour and a server reload we use preventDefault

handleSubmit = e => {
  e.preventDefault();
  ....
};

render() {
  return (
    <form onSubmit={this.handleSubmit}>
      <div className="formGroup">
        <label htmlFor="username">Username</label>
        <input id="username" type="text" className="form-control"/>
      </div>

      <input className="btn btn-primary" type="submit"> submit </input>
    )
};

Bind form element to state

  state = { 
       account : 
        {      
            username : '',  
            password:''
        }
     }

and in input set value to the state we defined

<input value={this.state.account.username} 
           onChange={this.handleChange}
            id="username" ...

and implement handleChange

  handleChange (e) => {
     const account = {... this.state.account};
    account.username = e.currentTarget.value;
    this.setState({account});
  }

instead of defining one by one change second line to

  account[e.currentTarget.name] = e.currentTarget.value;

also form elements must have name tag to do this.

<input id="username" name="ussername" ...

a bit of refactoring

const { account } = this.state;

so form elements can be

<input value={account.username} 
           onChange={this.handleChange}
            id="username" ...

and in handleChange :

  handleChange ({ currentTarget: input }) => {
     const account = {... this.state.account};
    account[input.name] = input.value;
    this.setState({account});
  }



Accessing document object in React

Define a property for reference

  username = React.createRef();

Then assign this property to ref in input field

  <input ref="username" ....

to access it

const usr = this.username.currrent.value;

Like setting a focus

  componentDidMount(){
   this.username.current.focus();
 }
=== autoFocus ===
Instead of focus there is a better way 
 <input autoFocus id="username"....