11import React , {
22 SelectHTMLAttributes ,
33 OptionHTMLAttributes ,
4- useContext ,
54 Ref ,
5+ useContext ,
6+ useRef ,
7+ ChangeEvent ,
68} from 'react' ;
79import classnames from 'classnames' ;
810import { FormElement , FormElementProps } from './FormElement' ;
911import { FieldSetColumnContext } from './FieldSet' ;
10- import { useFormElementId } from './hooks' ;
12+ import { useEventCallback , useFormElementId } from './hooks' ;
1113import { createFC } from './common' ;
1214
1315/**
@@ -20,32 +22,53 @@ export type SelectProps = {
2022 error ?: FormElementProps [ 'error' ] ;
2123 elementRef ?: Ref < HTMLDivElement > ;
2224 selectRef ?: Ref < HTMLSelectElement > ;
25+ onValueChange ?: ( value : string , prevValue ?: string ) => void ;
2326} & SelectHTMLAttributes < HTMLSelectElement > ;
2427
2528/**
2629 *
2730 */
2831export const Select = createFC < SelectProps , { isFormElement : boolean } > (
2932 ( props ) => {
30- const { id : id_ } = props ;
33+ const {
34+ id : id_ ,
35+ className,
36+ label,
37+ required,
38+ error,
39+ cols,
40+ elementRef,
41+ selectRef,
42+ children,
43+ onChange : onChange_ ,
44+ onValueChange,
45+ ...rprops
46+ } = props ;
3147 const id = useFormElementId ( id_ , 'select' ) ;
3248 const { isFieldSetColumn } = useContext ( FieldSetColumnContext ) ;
33- const { label, required, error, cols, elementRef, ...rprops } = props ;
34- if ( isFieldSetColumn || label || required || error || cols ) {
35- const formElemProps = { id, label, required, error, cols, elementRef } ;
36- return (
37- < FormElement { ...formElemProps } >
38- < Select { ...{ ...rprops , id } } />
39- </ FormElement >
40- ) ;
41- }
42- const { className, selectRef, children, ...rprops2 } = rprops ;
49+ const prevValueRef = useRef < string > ( ) ;
50+ const onChange = useEventCallback ( ( e : ChangeEvent < HTMLSelectElement > ) => {
51+ onChange_ ?.( e ) ;
52+ onValueChange ?.( e . target . value , prevValueRef . current ) ;
53+ prevValueRef . current = e . target . value ;
54+ } ) ;
4355 const selectClassNames = classnames ( className , 'slds-select' ) ;
44- return (
45- < select ref = { selectRef } id = { id } className = { selectClassNames } { ...rprops2 } >
56+ const selectElem = (
57+ < select
58+ ref = { selectRef }
59+ id = { id }
60+ className = { selectClassNames }
61+ onChange = { onChange }
62+ { ...rprops }
63+ >
4664 { children }
4765 </ select >
4866 ) ;
67+ if ( isFieldSetColumn || label || required || error || cols ) {
68+ const formElemProps = { id, label, required, error, cols, elementRef } ;
69+ return < FormElement { ...formElemProps } > { selectElem } </ FormElement > ;
70+ }
71+ return selectElem ;
4972 } ,
5073 { isFormElement : true }
5174) ;
0 commit comments