I was trying to add the functionality that when i click on the selected radio button again it should get deselected, but my logic is not working that what i have did in handleRadioChange function.
SO the expected behaviour should be that when i click on selected button again it should get deslected.
As this is a reusable component and i wanted that functionality can some one help how to do this.
code
import {
FormControl,
FormControlLabel,
Radio,
RadioGroup,
} from '@material-ui/core'
import clsx from 'clsx'
import React from 'react'
import { useStyles } from './index.styles'
import OpenInNewIcon from '@mui/icons-material/OpenInNew'
import { isEmpty } from 'lodash'
import { RadioButtonType } from 'labrav-react-components'
import { RadioButtonGroupMapping } from 'labrav-react-components'
export type RadioButtonsProps = {
checkedValue?: { key: string; value: string }
handleChange: (event: React.ChangeEvent<HTMLInputElement>) => void
radioButtonMappings: RadioButtonGroupMapping[]
customChild?: JSX.Element
}
export const NewRadioButtons: React.FC<RadioButtonsProps> = ({
checkedValue,
handleChange,
radioButtonMappings,
customChild,
}) => {
const classes = useStyles()
const handleRadioChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const selectedValue = event.target.value
const isSameValue = selectedValue === checkedValue?.value
if (isSameValue) {
handleChange({
target: { value: ''},
} as React.ChangeEvent<HTMLInputElement>)
} else {
handleChange(event)
}
}
return (
<FormControl>
<RadioGroup
aria-labelledby="radio-buttons-group"
name="radio-buttons-group"
value={checkedValue ? checkedValue?.value :''}
onChange={handleRadioChange}
data-testid="radio-group"
row
className={classes.root}
>
{radioButtonMappings.map(radioButtonMapping => {
return (
<div
key={radioButtonMapping.key}
>
<FormControlLabel
value={radioButtonMapping.key}
control={<Radio className={classes.radio} />}
label={radioButtonMapping.label}
className={classes.radioLabel}
data-testid="radio-label"
disabled={radioButtonMapping?.disabled || false}
/>
{radioButtonMapping.key !== RadioButtonType.CUSTOM &&
!isEmpty(radioButtonMapping.url) && (
<a
style={{ height: '18px' }}
href={radioButtonMapping.url}
target="_blank"
>
<OpenInNewIcon className={classes.openNewIcon} />
</a>
)}
{checkedValue &&(checkedValue.key === radioButtonMapping.key &&
radioButtonMapping.type === RadioButtonType.CUSTOM) ? (
<>{customChild}</>
) : null}
</div>
)
})}
</RadioGroup>
</FormControl>
)
}