0

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) }   />
      );
  }

}

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

could you add more code how someaction will trigger.. i am not clear on this
I mean by triggering a new action, doing the same as you did for fetch data and adding them to the store but in this case you are not fetching data, you will only trigger the new action and the reducer which handle projects should act according to the new action and make the change

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.