1

I'm building a react component that has two optional props. While both props are optional, I would want for at least one of them to be passed at runtime. If both props are missing then the component should fail rendering. For context, I'm using Typescript react with functional components and my props are defined as interfaces. Look at the sample code below that defines props for my autosuggest component

interface AutosuggestProps {
    name: string;
    placeholder: string;
    suggestions?: any[];
    onChange?: (value: string) => void;
    onSuggestionSelected: (value: object) => void;
    httpSearch?: (abortController: AbortController, query: string) => Promise<FetchResponse<any>>
}

The Autosuggest component can be used in two ways

  1. The creator of the component at runtime may choose to listen to an onChange events then performs the search and then updates the suggestions via the suggestions props or
  2. Let the Autosuggest component handle the search and update it's own state and not rely on the suggestions props been passed to it.

I've decleared onChange and httpSearch as optional props but I would want for at least one of them to be present else the component should fail rendering. I mean the Autosuggest should either be called like this

<Autosuggest
    name="person"
    placeholder="Find person"
    onChange={handleChange}
    suggestions={suggestions}
/>

Or

<Autosuggest
    name="person"
    placeholder="Find person"
    httpSearch={searchPerson}
/>

But never like this

<Autosuggest
    name="person"
    placeholder="Find person"
/>
Stylishcoder
  • 1,142
  • 1
  • 11
  • 21
  • I was wondering the same thing to be able to do `` or `` instead of ``. I'm just writing that here because I think it's a much simpler example of the same problem ;-) – Sheraff Oct 18 '20 at 07:19

0 Answers0