Iam creating a Dropdown list in react-redux and saving the selected state of the Dropdown to use the that value in my App.
But while creating a call for action function, Iam stuck and can store the value required:
RoleReducer which has the json object
RoleReducer.js
export default function () {
return [
{
key:1,
value: "abc"
},
{
key:2,
value: "def"
},
{
key:3,
value: "hij"
}
]
}
Action component where the selected dropdown will be saved
selectedRoleAction.js
const selectedRoleAction = (role) => {
console.log("role selected is: ", role.key);
return {
type: "ROLE_SELECTED",
payload: role,
}
};
export default selectedRoleAction;
Component where the dropdown is created and the actions will be used
RoleDropDown.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { withRouter } from 'react-router-dom';
import ActionsReducer from '../../../reducers/actionsReducer';
import rolesReducer from '../../../reducers/rolesReducer';
import selectedRoleAction from '../../../actions/selectedRoleAction';
import ActionsActions from '../../../actions/actionsActions';
class RoleDropdown extends Component {
createDropdownlist() {
return this.props.roles.map((role) => {
return (
<option value={role.value}>{role.value}</option>
)
})}
render() {
return (
<div>
<select
onChange={() => this.props.selectedRoleAction(role)}
className="form-control">
<option>Please select a role</option>
{this.createDropdownlist()}
</select>
</div>
)
}
}
function mapStateToProps(state) {
return {
roles: state.roles,
};
}
function matchDispatchToProps(dispatch) {
return bindActionCreators({selectedRoleAction:selectedRoleAction}, dispatch)
}
export default connect(mapStateToProps, matchDispatchToProps)(withRouter(RoleDropdown));
The error in output
Error
Failed to compile
./src/containers/MainContent/Dashboard/RoleDropdown.js
Line 36: 'role' is not defined no-undef
Search for the keywords to learn more about each error.
As you can see from the error message it says role
is not defined .
selecting an option in select
will fire onChange
with the selectedOption
as your first argument. so you need to change your code as
onChange={(role) => this.props.selectedRoleAction(role)}
You were trying to pass the role
which as not there that's why the error message hinted you saying 'role' is not defined no-undef
as it was not able to find the role
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments