diff --git a/.changeset/tasty-hotels-hunt.md b/.changeset/tasty-hotels-hunt.md new file mode 100644 index 0000000..0c9bcc3 --- /dev/null +++ b/.changeset/tasty-hotels-hunt.md @@ -0,0 +1,5 @@ +--- +"@openfun/cunningham-react": patch +--- + +fix controlled searchable select triggering onChange undefined diff --git a/packages/react/src/components/Forms/Select/mono-common.tsx b/packages/react/src/components/Forms/Select/mono-common.tsx index 0f15a6e..f15bf9b 100644 --- a/packages/react/src/components/Forms/Select/mono-common.tsx +++ b/packages/react/src/components/Forms/Select/mono-common.tsx @@ -1,4 +1,4 @@ -import React, { HTMLAttributes, useEffect } from "react"; +import React, { HTMLAttributes } from "react"; import { UseSelectReturnValue } from "downshift"; import classNames from "classnames"; import { useCunningham } from ":/components/Provider"; @@ -73,17 +73,6 @@ export const SelectMonoAux = ({ const { t } = useCunningham(); const labelProps = downshiftReturn.getLabelProps(); - // When component is controlled, this useEffect will update the local selected item. - useEffect(() => { - if (downshiftProps.initialSelectedItem !== undefined) { - return; - } - const optionToSelect = options.find( - (option) => optionToValue(option) === value, - ); - downshiftReturn.selectItem(optionToSelect ?? null); - }, [value]); - return (
{ downshiftReturn.inputValue, ]); + // When component is controlled, this useEffect will update the local selected item. + useEffect(() => { + if (props.downshiftProps.initialSelectedItem !== undefined) { + return; + } + const optionToSelect = props.options.find( + (option) => optionToValue(option) === props.value, + ); + downshiftReturn.selectItem(optionToSelect ?? null); + }, [props.value, props.options, props.downshiftProps]); + const inputProps = downshiftReturn.getInputProps({ ref: inputRef, disabled: props.disabled, diff --git a/packages/react/src/components/Forms/Select/mono-simple.tsx b/packages/react/src/components/Forms/Select/mono-simple.tsx index 87c6457..22ed327 100644 --- a/packages/react/src/components/Forms/Select/mono-simple.tsx +++ b/packages/react/src/components/Forms/Select/mono-simple.tsx @@ -1,7 +1,8 @@ import { useSelect } from "downshift"; -import React from "react"; +import React, { useEffect } from "react"; import { optionToString, + optionToValue, SelectMonoAux, SubProps, } from ":/components/Forms/Select/mono-common"; @@ -13,6 +14,17 @@ export const SelectMonoSimple = (props: SubProps) => { itemToString: optionToString, }); + // When component is controlled, this useEffect will update the local selected item. + useEffect(() => { + if (props.downshiftProps.initialSelectedItem !== undefined) { + return; + } + const optionToSelect = props.options.find( + (option) => optionToValue(option) === props.value, + ); + downshiftReturn.selectItem(optionToSelect ?? null); + }, [props.value, props.options, props.downshiftProps]); + return ( ", () => {
Value = {value}|
+