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
- The creator of the component at runtime may choose to listen to an
onChangeevents then performs the search and then updates the suggestions via thesuggestionsprops or - Let the
Autosuggestcomponent handle the search and update it's own state and not rely on thesuggestionsprops 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"
/>