I am working on a React project using TypeScript. They wrapped the react-select component into another component. The wrapped component is the following:
import * as React from "react";
import Select from "react-select";
import { Props as SelectProps } from "react-select/lib/Select";
export interface SelectValue {
label: string;
value: string;
}
export interface SelectFieldProps<TValue> extends SelectProps<TValue> {
label?: string;
}
type GenericSelectField<TValue> = React.StatelessComponent<
SelectFieldProps<TValue>
>;
const SelectField: GenericSelectField<SelectValue> = ({
label = "",
...rest
}) => (
<div className="react-select-wrapper">
{label ? <span className="input__label">{label}</span> : null}
<Select classNamePrefix="react-select" {...rest} />
</div>
);
export default SelectField;
I would like to access the method blur
from react-select:
React-select exposes two public methods:
...
blur() - blur the control programatically
But, I don't know how to expose it in my Component, so I could invoke it. Any ideas?
You can use ref
property on the Select
component to get a reference to the instance of this component.
Then you can call the blur
method of this instance.
const SelectField: GenericSelectField<SelectValue> = ({label = "",...rest}) => {
const selectEl = React.useRef(null);
// this function could be a callback
function handleBlur() {
selectEl.current.blur();
}
return (
<div className="react-select-wrapper">
{label ? <span className="input__label">{label}</span> : null}
<Select ref={selectEl} classNamePrefix="react-select" {...rest} />
</div>
);
}
export default SelectField;
If you need to access the blur
method outside of your SelectField
component, you could use forwardRef to reference Select
instead of the SelectField
.
const SelectField = (props, ref) => {
const {label = "",...rest} = props;
const selectEl = React.useRef(null);
return (
<div className="react-select-wrapper">
{label ? <span className="input__label">{label}</span> : null}
<Select ref={ref} classNamePrefix="react-select" {...rest} />
</div>
);
}
export default React.forwardRef(SelectField);
Then you can call the blur
method with the reference of the SelectField
component :
const ref = React.createRef();
<SelectField ref={ref} label=""/>;
ref.blur();
If I understand this correctly you want to trigger Select's blur() inside of SelectField.
There are many ways for example parent-child-binding it via props. Here is a discussion about this:
Call child method from parent
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With