Created
February 17, 2018 17:09
-
-
Save jsjoeio/d3e40d077a4b950e66790f3bd818ee49 to your computer and use it in GitHub Desktop.
Thinkful - React interactivity - AddForm component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import './add-form.css'; | |
//First, we create a class component called AddForm | |
export default class AddForm extends React.Component { | |
constructor(props) { | |
super(props); | |
//when we define the state, we want to set a default value for text because we want to control the input. | |
this.state = { | |
editing: false, | |
text: '' | |
} | |
} | |
onSubmit(event) { | |
event.preventDefault(); | |
//we utilize the onSubject prop/method which will allow us to submit the text | |
const text = this.state.text; | |
console.log(text); | |
//later we reset the state back to the default value, '' | |
this.setState({ | |
text: '' | |
}); | |
} | |
//this prop/method will allow us to set the text to whatever we pass to the function. | |
setText(text) { | |
this.setState({ | |
text | |
}) | |
} | |
//this allows us to edit the text by setting editing to true. | |
setEditing(editing) { | |
this.setState({ | |
editing | |
}); | |
} | |
render() { | |
if (!this.state.editing) { | |
//here it may look a little confusing but we're doing this to make the component more reusable. we can pass a 'type' to the AddForm component so that we can add forms for lists AND cards - genius! | |
const text = `Add a ${this.props.type}`; | |
return ( | |
<div className="add-button" | |
onClick={() => this.setEditing(true)}> | |
<a href="#">{text}...</a> | |
</div> | |
); | |
} | |
const label = `Enter a ${this.props.type}`; | |
return ( | |
<form className="card add-form" onSubmit={(e) => this.onSubmit(e)}> | |
<input type="text" | |
value={this.state.text} | |
//here, we utilize the onChange prop which is called when the value in the input is changed. We then update it instantly. | |
onChange={e => this.setText(e.target.value)} | |
aria-label={label} | |
/> | |
<button>Add</button> | |
//if the user hits the cancel button, setEditing to false because they no longer want to edit. | |
<button type="button" onClick={() => this.setEditing(false)}> | |
Cancel | |
</button> | |
</form> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment