I have this component that renders multi choice checkboxes and it works well. But I would like to have the option to specify that only one checkbox can be checked.
How can I change this component to be that dynamic
I am using this component with redux-form lib
Code
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
class CheckboxGroup extends PureComponent {
constructor(props) {
super(props)
this.checkboxGroup = this.checkboxGroup.bind(this)
}
checkboxGroup() {
const {
id,
options,
input,
} = this.props
return options.map(option => (
<div key={option.id}>
<div className="checkbox-container">
<input
type="checkbox"
id={id}
name={`${input.name}[${option.id}]`}
value={option.name}
checked={input.value.indexOf(option.name) !== -1}
onChange={(event) => {
const newValue = [...input.value]
if (event.target.checked) {
newValue.push(option.name)
} else {
newValue.splice(newValue.indexOf(option.name), 1)
}
return input.onChange(newValue)
}}
/>
{option.name && <span>{option.name}</span>}
</div>
</div>
))
}
render() {
const { label, id } = this.props
return (
<div className="input-container">
<label htmlFor={id}>
<span>{label}</span>
</label>
{this.checkboxGroup()}
</div>
)
}
}
CheckboxGroup.propTypes = {
options: PropTypes.arrayOf(PropTypes.object),
input: PropTypes.shape({
}).isRequired,
id: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
}
export default CheckboxGroup
Aucun commentaire:
Enregistrer un commentaire