Files
payload/test/admin/collections/CustomFields/fields/Select/CustomInput.tsx
Paul 1c4eba41b7 fix(ui): allow selectinputs to reset to their initial values if theres no provided value (#11252)
When reusing the SelectInput component from the UI package, if you set
value to `''` it will continue to display the previously selected value
instead of clearing out the field as expected.

The ReactSelect component doesn't behave in this way and instead will
clear out the field.

This fix addresses this difference by resetting `valueToRender` inside
the SelectInput to null.
2025-02-18 16:40:29 +00:00

62 lines
1.3 KiB
TypeScript

'use client'
import type { OptionObject, UIField } from 'payload'
import { SelectInput, useField } from '@payloadcms/ui'
import { useEffect, useMemo } from 'react'
interface Props {
field: UIField
path: string
required?: boolean
}
const selectOptions = [
{
label: 'Option 1',
value: 'option-1',
},
{
label: 'Option 2',
value: 'option-2',
},
]
export function CustomInput({ field, path, required = false }: Props) {
const { setValue, value } = useField<string>({ path })
const options = useMemo(() => {
const internal: OptionObject[] = []
internal.push(...selectOptions)
return internal
}, [])
return (
<div className="custom-select-input">
<SelectInput
label={field.label}
name={field.name}
onChange={(option) => {
const selectedValue = (Array.isArray(option) ? option[0]?.value : option?.value) || ''
setValue(selectedValue)
}}
options={options}
path={path}
required={required}
value={value}
/>
<button
className="clear-value"
onClick={(e) => {
e.preventDefault()
setValue('')
}}
type="button"
>
Click me to reset value
</button>
</div>
)
}