I have a array that for every item in the array a drop down list is dynamically generated. Right now each drop down list share the same toggle boolean so they all open and close and the same time, how can I make this work individually?
I map each object to a index here and then start creating dropdowns:
{Object.keys(props.totalWorkload.options).map((item, i) => (
<WorkloadOptions
key={i}
cnt={i}
appendChoiceList={props.appendChoiceList}
modalDropDown={props.modalDropDown}
toggleDropDown={props.toggleDropDown}
totalWorkloadOptions={props.totalWorkload.options[item]}
/>
))}
When the Drop Down options component is created I pass the index to a function:
<div>
<Dropdown isOpen={props.modalDropDown} toggle={props.toggleDropDown.bind(props.cnt)}>
<DropdownToggle caret>{props.totalWorkloadOptions.optionTitle}</DropdownToggle>
<DropdownMenu>
{props.totalWorkloadOptions.options.map(op => (
// tslint:disable-next-line:no-invalid-this
// tslint:disable-next-line:jsx-no-lambda
<DropdownItem key={op} onClick= {() => props.appendChoiceList(props.totalWorkloadOptions.optionTitle, op)}>
{op}
</DropdownItem>
))}
</DropdownMenu>
<strong> {props.totalWorkloadOptions.optionDescription} </strong>
</Dropdown>
<br />
</div>
The it will arrrive at the following functuion and console log the index and then set the appropriate toggle value in an array to true/false:
toggleDropDown = (index: any) => {
console.log('triggered!:' + index);
let clicked = this.state.modalDropDownClicked;
// tslint:disable-next-line:no-conditional-assignment
if (clicked[index]=!clicked[index]){
this.setState({ modalDropDownClicked: !this.state.modalDropDown[index] });
}
};
I can recommend the following pattern to toggle dynamically created elements: