Skip to content

Instantly share code, notes, and snippets.

@alx8437
Created May 20, 2020 08:25
Show Gist options
  • Save alx8437/4f0717da31fc9c5fc6b5a4e2eb3900ff to your computer and use it in GitHub Desktop.
Save alx8437/4f0717da31fc9c5fc6b5a4e2eb3900ff to your computer and use it in GitHub Desktop.
import React from 'react';
class AddNewItemForm extends React.Component {
constructor() {
super();
}
state = {
error: false,
inputValue: ''
}
newInputValue = (e) => {
this.setState({inputValue: e.currentTarget.value});
this.setState({
error: false
})
}
onAddItemClick = () => {
let newText = this.state.inputValue.trim();
if (newText === "") {
this.setState({
error: true
})
} else {
this.props.addItem(newText);
this.state.inputValue = '';
}
}
onKeyPress = (e) => {
if (e.key === "Enter") {
this.onAddItemList();
}
}
render = () => {
let classToError = this.state.error === true ? "error" : "";
return (
<div className="todoList-header">
<div className="todoList-newTaskForm">
<input
value={this.state.inputValue}
onChange={this.newInputValue}
className={classToError}
type="text"
placeholder="New item name"
onKeyPress={this.onKeyPress}
/>
<button
onClick={this.onAddItemClick}
>Add
</button>
</div>
</div>
)
}
}
export default AddNewItemForm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment