Complete Guide to Working With Forms In Reactjs

TextArea

In HTML, the value of <textarea> is usually set using its children:

<textarea>This is the description.</textarea>

For HTML, this easily allows developers to supply multiline values. However, since React is JavaScript, you do not have string limitations (you use \n if you want newlines, for example). To keep consistent across other form elements, React uses the value prop to set <textarea> values:

<textareavalue="This is a description." />

Select

In HTML, you set the selected option using the “selected” attribute on the option tag. In React, in order to make components easier to manipulate, the following format is adopted instead:

<selectvalue="B">
<optionvalue="A">Mobile</option>
<optionvalue="B">Work</option>
<optionvalue="C">Home</option>
</select>

Uncontrolled Components

Controlled components adhere to React’s principles and have their advantages. While uncontrolled components are an anti-pattern for how most other components are constructed in React, sometimes you don’t need to oversee the user input field by field.

This is especially true in longer forms, where you want to let the user fill in the fields and then process everything when the user is done.

Any input that does not supply a value is an uncontrolled component, and the value of the rendered element will reflect the user’s input. For example,

return (
<form>
<div className="formGroup">
Name: <input name="name" type="text" />
</div>
<div className="formGroup">
E-mail: <input name="email" type="mail" />
</div>
<button type="submit">Submit</button>
</form>
)

will render two input fields that start off with an empty value. Any user input will be immediately reflected by the rendered elements.

ImageTip If you want to set up an initial value for an uncontrolled form component, use the defaultValue prop instead of value.

It’s still possible to handle uncontrolled component forms using onSubmit, like so:

handleSubmit(event) {
console.log("Submitted values are: ",
event.target.name.value,
event.target.email.value);
event.preventDefault();
}

render() {
return(
<form onSubmit={this.handleSubmit}>
<divclassName="formGroup">
Name: <inputname="name" type="text" />
</div>
<divclassName="formGroup">
E-mail: <inputname="email" type="mail" />
</div>
<buttontype="submit">Submit</button>
</form>
)
}

 

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares