Last active
June 21, 2017 18:48
-
-
Save BolajiOlajide/477f0680ff391c085b83ba16182bca9d to your computer and use it in GitHub Desktop.
Manually dispatching actions
This file contains 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 PropTypes from "prop-types"; | |
import {connect} from "react-redux"; | |
import * as courseActions from "../../actions/courseAction"; | |
class CoursesPage extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
course: {title: " "} | |
}; | |
this.onTitleChange = this.onTitleChange.bind(this); | |
this.onClickSave = this.onClickSave.bind(this); | |
} | |
onTitleChange(event) { | |
const course = this.state.course; | |
course.title = event.target.value; | |
this.setState({course: course}); | |
} | |
onClickSave() { | |
// since we didn't define a mapDispatchToProps function, connect automatically adds a dispatch prop to the | |
// component. | |
this.props.dispatch(courseActions.createCourse(this.state.course)); | |
} | |
courseRow(course, index) { | |
return ( | |
<div key={index}> | |
{course.title} | |
</div> | |
); | |
} | |
render() { | |
debugger; | |
return ( | |
<div> | |
<h1> Courses </h1> | |
{this.props.courses.map(this.courseRow)} | |
<h2> Add Course </h2> | |
<input type="text" onChange={this.onTitleChange} value={this.state.course.title} /> | |
<input type="submit" value="Save" onClick={this.onClickSave} /> | |
</div> | |
); | |
} | |
} | |
CoursesPage.propTypes = { | |
dispatch: PropTypes.func.isRequired, | |
courses: PropTypes.array.isRequired | |
}; | |
const mapStateToProps = (state, ownProps) => { | |
return { | |
courses: state.courses | |
}; | |
}; | |
export default connect(mapStateToProps)(CoursesPage); | |
//another way to do this is: | |
// connectedStateAndProps = connect(mapStateToProps, mapDispatchToProps); | |
// export default connectedStateAndProps(CoursesPage); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment