1
- import React from 'react' ;
1
+ import React , { Component } from 'react' ;
2
2
import { connect } from 'react-redux' ;
3
3
import { addTodo } from '../actions' ;
4
4
5
- const AddTodo = ( { dispatch } ) => {
6
- let input ;
5
+ class TodoForm extends Component {
6
+ constructor ( ) {
7
+ super ( ) ;
8
+ this . state = {
9
+ todo : ""
10
+ }
11
+ this . handleSubmit = this . handleSubmit . bind ( this ) ;
12
+ this . handleChange = this . handleChange . bind ( this ) ;
13
+ }
7
14
8
- const handleSubmit = e => {
15
+ handleChange ( e ) {
9
16
e . preventDefault ( ) ;
10
- if ( ! input . value . trim ( ) ) return ;
11
- dispatch ( addTodo ( input . value ) ) ;
12
- input . value = ""
17
+ this . setState ( { [ e . target . id ] : e . target . value } )
18
+ }
19
+
20
+ handleSubmit ( e ) {
21
+ e . preventDefault ( ) ;
22
+ if ( this . state . todo === "" ) return ;
23
+ this . props . addTodo ( this . state . todo ) ;
24
+ this . setState ( { todo : "" } ) ;
25
+ }
26
+
27
+ render ( ) {
28
+ return (
29
+ < div >
30
+ < form >
31
+ < input
32
+ type = "text"
33
+ className = "form-control col-6 d-inline"
34
+ id = "todo"
35
+ value = { this . state . todo }
36
+ onChange = { this . handleChange }
37
+ placeholder = "Todo What?"
38
+ />
39
+ < button type = "submit" className = "btn btn-primary ml-2" onClick = { this . handleSubmit } > Add</ button >
40
+ </ form >
41
+ </ div >
42
+ ) ;
43
+ }
44
+ }
45
+
46
+ function mapDispatchToProps ( dispatch ) {
47
+ return {
48
+ addTodo : todo => dispatch ( addTodo ( todo ) )
13
49
}
14
-
15
- return (
16
- < div >
17
- < form onSubmit = { handleSubmit } >
18
- < input type = "text" className = "form-control col-6 d-inline" ref = { node => ( input = node ) } placeholder = "Todo What?" />
19
- < button type = "submit" className = "btn btn-primary ml-2" > Add</ button >
20
- </ form >
21
- </ div >
22
- )
23
50
}
24
51
25
- export default connect ( ) ( AddTodo ) ;
52
+ export default connect ( null , mapDispatchToProps ) ( TodoForm ) ;
0 commit comments