I've got my custom icon toggle component:
class ToggleIconSwitch extends Component {
render() {
const { leftIcon, rightIcon, name, handleOptionChange, checked, leftValue, rightValue } = this.props
return (
<div className="toggle-switch-icon-wrapper">
<div className="toggle-switch">
<input
type="radio"
name={ name }
id={ leftValue }
value={ leftValue }
checked={ checked === leftValue }
onChange={ handleOptionChange }
/>
<label htmlFor={ leftValue } className="icon">{ leftIcon }</label>
<input
type="radio"
name={ name }
id={ rightValue }
value={ rightValue }
checked={ checked === rightValue }
onChange={ handleOptionChange }
/>
<label htmlFor={ rightValue } className="icon">{ rightIcon }</label>
</div>
</div>
)
}
}
and then I've got multiple toggles on some page and I want to handle each toggle input change...
_.map(acl, (permission) => {
return (
<div className="row" key={ permission.id } >
<ToggleIconSwitch
name={ _.toString(permission.id) }
leftIcon={ <VisibilityIcon className="svg" /> }
leftValue="read"
rightIcon={ <CreateIcon className="svg"/> }
rightValue="write"
checked={ permission.permission }
handleOptionChange={ this.toggleUsersPermission }
/>
<IconButton
aria-label="Delete"
className="icon-button animate"
onClick={ this.openDeleteDialog(permission) }
>
<CloseIcon className="icon-button-red" />
</IconButton>
</div>
)
})
The problem is that the toggleUsersPermission function is always called only for the first ToggleIconSwitch component, even if I click on another ToggleIconSwitch. It also does not react when I click on the other toggle component's label, which is checked in first toggle component in list. I'm always getting event.target of the first toggle in list ... Why?
Try to click on the icons in CodeSandbox here
permission.idvalues unique? Thekeyproperty needs to be unique for each sibling element dynamically created like this. Otherwise React gets all confused.toggleUsersPermissionand then have that return a handle function which "knows" which element to work with.this.toggleUsersPermission.bind(this, permission.id)ashandleOptionChangefunction, but it's same as before, it doesn't handle any toggle clicks but first, and on the other toggles it handles clicking on the unchecked value (of first toggle), but it always returnspermission.idof the first toggle