React uncheck input type check on specific condition

I have 3 inputs type check fields

  • input pick man
  • input pick woman
  • input pick special

The user shall only be able to check a man or woman + special.

The user shall not be able to pick man and woman.

If the users pick man first and wants to pick woman afterwards, the man input shall be unchecked and the woman checkbox shall be picked / checked.

Basically I have following conditions:

  • man + special – allowed
  • woman + special – allowed
  • man + woman – not allowed (only one of them can be picked)

How can I implement this?

So far I have done this:


const TargetViewCard = ({ onChangeTraits }: Props) => {
  const { targetGroupData, targetGroupIsLoading, targetGroupIsError } = useTargetGroupData()
  const [selectedTarget, setSelectedTarget] = useState<ITargetItem[]>([])

  const findTarget = (id: string) => targetGroupData.items.find((target: ITargetItem) => target.id === parseInt(id))

  const checked = (item: ITargetItem) => !!selectedTarget?.find(c => c.id === item.id)

  const toggleTarget = (e: ChangeEvent<HTMLInputElement>) => {
    const target = findTarget(e.target.value)

    let sTarget
    if (selectedTarget.includes(target)) {
      sTarget = selectedTarget.filter(selectedTarget => selectedTarget.id !== target.id)
      setSelectedTarget(selectedTarget.filter(selectedTarget => selectedTarget.id !== target.id))
    } else {
      sTarget = [...selectedTarget, target]
      setSelectedTarget([...selectedTarget, target])
    }

    onChangeTraits(sTarget)
  }

render(
    ...
    {targetGroupData.items.map((item: ITargetItem) => (
        <div key={item.name} className="py-4">
            <label htmlFor={`target-item-${item.id}`}>
            <div>
                {item.name}
                <input
                id={`target-item-${item.id}`}
                name={`target-item-${item.id}`}
                type="checkbox"
                className="hidden"
                value={item.id}
                onChange={e => toggleTarget(e)}
                />
            </div>
            </label>
        </div>
    ))}
)