Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a public method from a wrapped Component using TypeScript?

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?

like image 997
Aldo Avatar asked Oct 16 '22 15:10

Aldo


2 Answers

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();
like image 98
Olivier Boissé Avatar answered Oct 19 '22 03:10

Olivier Boissé


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

like image 41
p0rter Avatar answered Oct 19 '22 02:10

p0rter