Guilherme Moretto
Guilherme Moretto

Reputation: 103

My select component dont't perform onChange (React.js)

I have a React Select component (react-select.com) that by default performs a onChange action. What I want to do is to set another action to be executed along with the first one.

The problem is: when I pass a funtion to onChange, it overrides the another one. I tried to do some changes but it didn't work, so I will show my code here without them.

My component:

function SelectInput(props: any) {
const [field, defaultValue, {setValue}] = useField(props.field);

const handleChange = (value: any) => {
    setValue(value.value);
};

const {options} = props;

return (
    <Select
        styles={styles}
        className="react-select-container"
        classNamePrefix="react-select"
        options={options}
        name={field.name}
        onChange={handleChange}
        value={
            options
                ? options.find(
                      (option: any) => option.value === field.value
                  )
                : ''
        }
        {...props}
    />
);
}

How I want to use it:

{
<Field // this comes from Formi
    name="type"
    component={SelectInput} // here I tell Formik to render my component, it works the same as rendering it directly
    placeholder=" "
    options={options}
    onChange={() => {MY_FUNCTION_HERE}} // I want to call this function and also the handleChange inside the component
/>
}

Upvotes: 1

Views: 195

Answers (1)

Cristian Riță
Cristian Riță

Reputation: 559

This is because you are passing {...props} to the Select component as the last prop. So the onChange function coming from the props will override the one you declared. Try this:

 <Select
        {...props}
        styles={styles}
        className="react-select-container"
        classNamePrefix="react-select"
        options={options}
        name={field.name}
        onChange={handleChange}
        value={
            options
                ? options.find(
                      (option: any) => option.value === field.value
                  )
                : ''
        }
    />

Upvotes: 1

Related Questions