Reputation: 7375
We have populated the checkbox items dynamically from calling api service through fetch. based upon the collection we will display the checkbox with checked state.
if i check/uncheck the checkbox how can i implement the handlechange event for dynamically populated checkbox items.
i want to get the current checkbox state. how can i get it
in checkboxcontainer.tsx
data.map(item => (
<label key={item.projectId} className="checkBoxcontainer">
<CheckBox name={item.projectName}
checked={item.checked} handleChange={this.handleChange} />
{item.projectName}<span className="checkmark"/>
</label>
Redux :
const mapStateToProps=({projects} : ApplicationState) => ({
data: projects.data
});
const mapDispatchToProps = (dispatch: Dispatch) => ({
fetchProjects: bindActionCreators(fetchProjects, dispatch),
});
const ProjectListContainer = connect(mapStateToProps,mapDispatchToProps)(ProjectContainer);
export { ProjectListContainer as ProjectContainer };
Handle change function:
handleChange(e :any) {
// how to maintain the checkbox state
}
import * as React from 'react';
interface IPropTypes {
type?: string,
name: string,
checked?: boolean,
handleChange(event: any): void;
}
class CheckBox extends React.Component<IPropTypes,{}> {
render() {
return (
<input type='checkbox' name={this.props.name} checked={this.props.checked}
onChange={ e => this.props.handleChange(e) } />
);
}
}
Upvotes: 0
Views: 1023
Reputation: 515
I suggest that the handleChange function passed to Checkbox
looks as follow:
handleChange={(e) => this.handleChange(e, item.projectId)}
And then in handleChange
you can grab if the checkbox is selected or not and then trigger an action with both the projectId
and the state of the checkbox
const isChecked = event.target.checked;
someAction(projectId, isChecked);
This action should change the data in your redux store
Upvotes: 1