I'm new to React, React Router (v4) and Redux. I'm trying to access a URL parameter from mapStateToProps(state, ownProps) by accessing ownProps.match.params.id but the params array is always empty. I've used the debugger to inspect ownProps and the id parameter that should be passed isn't anywhere in ownProps.
Here is a snippet from my routes:
<Switch>
<Route exact path='/' component={HomePage} />
<Route path='/about' component={AboutPage} />
<Route path='/course' component={ManageCoursePage} />
<Route path='/course/:id' component={ManageCoursePage} />
<Route path='/courses' component={CoursesPage} />
</Switch>
Here is the relevant code from ManageCoursePage.js:
class ManageCoursePage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
course: Object.assign({}, props.course),
errors: {},
};
}
}
function mapStateToProps(state, ownProps) {
const courseId = ownProps.match.params.id;
...
}
export default connect(mapStateToProps, mapDispatchToProps)(ManageCoursePage);
You have to flip the order of the following routes or set the
exactproperty to the first route./coursematches before/course/:idthats whyManageCoursePageis called without the id param. if you only want to match/coursein your first route and not/course/123you can set theexactproperty.