2

Trying to pass ref to my search component without any success. This is My component:

interface SearchInputProps {
  placeholder: string;
  onSearch: () => any;
}
// type TextInputProps = React.HTMLProps<TextInput>;

export const SearchInput: React.FC<SearchInputProps> = forwardRef<TextInput, SearchInputProps>(
  ({ placeholder, onSearch }, ref) => {
    const [searchText, setSearchText] = useState("");

    return (
      <View style={{ flex: 1, flexDirection: "row" }}>
        <View style={{ flexDirection: "row", alignItems: "center", flex: 1, padding: 5 }}>
          <Ionicons name="search" color={Colors.white} size={23} />
          <TextInput
            autoFocus
            placeholder={placeholder}
            placeholderTextColor={Colors.lightGrey2}
            style={{ marginLeft: 10, fontSize: 16, color: Colors.weakGrey, flex: 1 }}
            blurOnSubmit={false}
            value={searchText}
            onChangeText={(text) => {
              setSearchText(text);
              onSearch();
            }}
          ></TextInput>
          {searchText.length ? (
            <Ionicons
              name="close-circle"
              color={Colors.lightGrey}
              size={22}
              onPress={() => setSearchText("")}
              style={{ marginLeft: 5 }}
            />
          ) : null}
        </View>
      </View>
    );
  }
);

creating the ref:

const inputRef = useRef<TextInput>();

The component:

<SearchInput placeholder={"Search a user"} onSearch={() => setIsTyping(true)} ref={inputRef} />

I get this error:

Type '{ placeholder: string; onSearch: () => void; ref: MutableRefObject; }' is not assignable to type 'IntrinsicAttributes & SearchInputProps & { children?: ReactNode; }'. Property 'ref' does not exist on type 'IntrinsicAttributes & SearchInputProps & { children?: ReactNode; }

1 Answer 1

5
export const SearchInput: React.FC<SearchInputProps> = forwardRef<TextInput, SearchInputProps>(

The problem is that you've added an explicit type annotation to SearchInput which overrides the type created by forwardRef.

React.FC<SearchInputProps> means that this component can only accept props from SearchInputProps. It doesn't know anything about the ref. The correct type for the SearchInput variable uses ForwardRefExoticComponent instead of FC. It is:

React.ForwardRefExoticComponent<SearchInputProps & React.RefAttributes<TextInput>>

But I would recommend that you let the type of SearchInput be inferred rather than explicitly annotating it. Simply delete the : React.FC<SearchInputProps> from your code and it will work.

Typescript Playground Link

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.