An Introduction to Using Form Elements in React

React form components 101: What you need to know

Form Elements in React Need State

Coding the form elements bare-bones

export class ExploreForms extends React.Component {  render() {
return(
<div><h2>Form elements</h2>
<form action="/myform" method="post">
<p>
Textbox: <br />
<input type="text" name="test" />
</p>
<p>Textarea: <br />
<textarea name="textarea_1" value="My Textarea" />
</p>
<p>Checkbox: <br />
<input type="checkbox" name="category" value="category1" /> Cat1
<input type="checkbox" name="category" value="category2" /> Cat2
<input type="checkbox" name="category" value="category3" /> Cat3
</p>
<p>Radio: <br />
<input type="radio" name="location" value="location1" /> Loc1
<input type="radio" name="location" value="location2" /> Loc2
<input type="radio" name="location" value="location3" /> Loc3
</p>
<p>Select: <br />
<select name="product" defaultValue={2}>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
</p>
<input type="submit" value="Submit Form" />
</form>
</div>
);
}
}

Introducing onChange, defaultValue, and defaultChecked props

Textarea

render () {     
return (
<textarea id={this.props.id}
name={this.props.name}
defaultValue={this.state.value}
onChange={this.handleChange} />
);
}

Radio

...handleChange = () => {
this.setState({selected: !this.state.selected})
}
render () {
return (
<span>
<input
type="radio"
defaultChecked={this.state.selected}
onChange={this.handleChange}
id={this.props.id}
name={this.props.name}
/>
{this.props.label}
</span>
);
}

Checkbox

...handleChange = () => {
this.setState({checked: !this.state.checked})
}
render () {
return (
<span>
<input
type="checkbox"
defaultChecked={this.state.checked}
onChange={this.handleChange}
id={this.props.id}
name={this.props.name}
/>
{this.props.label}
</span>
);
}

Working with PropTypes and form elements

import PropTypes from 'prop-types';

Submitting a Form

export class MyForm extends React.Component {

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

console.log('submitting form. We need to validate it!');
}
render() {
return(
<form action="/myform"
method="post"
onSubmit={this.handleSubmit}>
//components here <input type="submit" value="Submit Form" /> </form>
)
}
}

Where to go from here

But there is a better way

Programmer and Author. Director @ JKRBInvestments.com. Creator of LearnChineseGrammar.com for iOS and Android.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store