69 lines
1.8 KiB
JavaScript

'use client'
import { useCallback } from 'react'
export default function QInput({ type, readOnly = false, options = [], value, onChange }) {
// options = options || [
// {
// id: 'one',
// name: 'Option 1',
// value: '111',
// },
// {
// id: 'two',
// name: 'Option 2',
// value: '222',
// },
// {
// id: 'three',
// name: 'Option 3',
// value: '333',
// },
// ]
const handleChange = useCallback(
(e, optionValue) => {
if (type === 'radio') {
onChange(e.target.value)
} else {
const newValue = value.includes(optionValue) ? value.filter((v) => v !== optionValue) : [...value, optionValue]
onChange(newValue)
}
},
[type, value, onChange],
)
const handleTextChange = useCallback(
(e) => {
onChange(e.target.value)
},
[onChange],
)
return (
<>
{type === 'text' ? (
<div className="mb5">
<input type={type} className="input-light" readOnly={readOnly ? true : false} value={value} onChange={handleTextChange} />
</div>
) : type === 'radio' || type === 'checkbox' ? (
<div className="flx mb5">
{options?.map((option) => (
<div key={option.name} className={`d-${type}-radio light mr5`}>
<input
type={type}
name={type === 'radio' ? 'radioGroup' : 'checkboxGroup'}
value={option.value}
id={option.id}
checked={type === 'radio' ? value === option.value : value.includes(option.value)}
onChange={(e) => handleChange(e, option.value)}
/>
<label htmlFor={option.id}>{option.name}</label>
</div>
))}
</div>
) : null}
</>
)
}