stream-saga/src/js/components/Form.jsx

91 lines
2.1 KiB
React
Raw Normal View History

2019-06-19 14:49:50 -04:00
import React, { Component } from "react"
import { connect } from "react-redux"
import uuidv1 from "uuid"
import { addArticle } from "../actions/index"
2019-06-21 00:59:25 -04:00
import { setCandidate } from "../actions/index"
2019-06-19 14:49:50 -04:00
function mapDispatchToProps(dispatch) {
return {
2019-06-21 00:59:25 -04:00
addArticle: article => dispatch(addArticle(article)),
setCandidate: candidate => dispatch(setCandidate(candidate))
2019-06-19 14:49:50 -04:00
}
}
class ConnectedForm extends Component {
constructor() {
super()
this.state = {
2019-06-21 00:59:25 -04:00
title: '',
2019-06-21 10:53:16 -04:00
candidate: ''
2019-06-19 14:49:50 -04:00
}
this.handleChange = this.handleChange.bind(this)
2019-06-21 00:59:25 -04:00
this.handleSubmit = this.handleSubmit.bind(this)
this.clickTrump = this.clickTrump.bind(this)
this.clickHilary = this.clickHilary.bind(this)
2019-06-19 14:49:50 -04:00
}
2019-06-21 10:53:16 -04:00
componentDidMount() {
this.props.setCandidate('Hillary Clinton')
this.setState({ candidate: 'Hillary Clinton'})
}
2019-06-19 14:49:50 -04:00
handleChange(event) {
this.setState({ [event.target.id]: event.target.value })
}
handleSubmit(event) {
event.preventDefault()
const { title } = this.state
const id = uuidv1()
2019-06-19 16:37:03 -04:00
2019-06-19 14:49:50 -04:00
this.props.addArticle({ title, id })
this.setState({ title: "" })
2019-06-21 00:59:25 -04:00
}
clickTrump(event) {
event.preventDefault()
this.props.setCandidate('Donald Trump')
this.setState({ candidate: 'Donald Trump' })
}
clickHilary(event) {
event.preventDefault()
this.props.setCandidate('Hillary Clinton')
this.setState({ candidate: 'Hillary Clinton' })
}
2019-06-19 14:49:50 -04:00
render() {
const { title } = this.state
return (
2019-06-21 00:59:25 -04:00
<div>
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="title">Title</label>
<input
type="text"
className="form-control"
id="title"
value={title}
onChange={this.handleChange}
/>
</div>
<button type="submit" className="btn btn-success btn-lg">
SAVE
</button>
</form>
<button onClick={this.clickTrump}>Donald Trump</button>
<button onClick={this.clickHilary}>Hillary Clinton</button>
<p>{this.state.candidate}</p>
</div>
)
}
2019-06-19 14:49:50 -04:00
}
const Form = connect(null, mapDispatchToProps)(ConnectedForm)
export default Form