Skip to content

Instantly share code, notes, and snippets.

@dennisja
Last active November 2, 2018 12:49
Show Gist options
  • Select an option

  • Save dennisja/67f474b2d30e7a679d9b6458f9634efd to your computer and use it in GitHub Desktop.

Select an option

Save dennisja/67f474b2d30e7a679d9b6458f9634efd to your computer and use it in GitHub Desktop.
A simple form to show lessons learned about JS when building a simple controlled form in react
// We make use of ES6 imports
import React, { Component, Fragment } from "react";
// we make use of ES6 classes and inheritance
class TodoForm extends Component {
// we make use of class variables to initialize state
state = {
todoName: ""
};
// we make use of class variables to define an event handler for automatic this binding
// we as well learn that an event handler is passed the event object,
handleInputChange = event => {
const { name, value } = event.target; // we learn about destructuring and the even object api
this.setState({ [name]: value }); // we learn about computed properties
};
handleAddToDo = event => {
// this method is called when the submit button is pressed
// But the submit button has no onclick
// This as well teaches us that clicking the submit button fires the submit event on the form it belongs
event.preventDefault(); // we learn about preventing default event behaviours by preventing the default form behaviour
// do add todo logic here
};
render() {
// we use object destructuring to ge the todoName from state
const { todoName } = this.state;
return (
<form onSubmit={this.handleAddToDo}>
<label htmlFor="todoName">Todo Name: </label>
<input
type="text"
name="todoName"
id="todoName"
placeholder="Name Your TODO"
onChange={this.handleInputChange}
value={todoName}
/>{" "}
<input type="submit" value="Add" />
</form>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment