Home > Net >  Typescript selection box object might possibly be undefined
Typescript selection box object might possibly be undefined

Time:06-09

I have a selection box and an array of tabs. I'm getting an error that it might be possibly undefined.

here are the tabs ( might be mutable in future) :

const tabs = [
  { name: "1 tab",  current: true },
  { name: "2 tab",  current: false },
  { name: "3 tab",  current: false },
];

here is the selection part:

 <label htmlFor="question-tabs" className="sr-only">
        Select a tab
      </label>
      <select
        id="question-tabs"
        className="block w-full"
        defaultValue={tabs.find((tab) => tab.current).name}
      >
        {tabs.map((tab) => (
          <option key={tab.name}>{tab.name}</option>
        ))}
      </select>

I'm having some issue with this line:

defaultValue={tabs.find((tab) => tab.current).name

the error says that the object might be possibly undefined. How can I check to see if it is undefined, and if so just put some default text?

I've tried something like this but it didn't work:

defaultValue={tabs ? tabs.find((tab) => tab.current).name : ''}

CodePudding user response:

find returns undefined if tabs doesn't contain tab. Using Optional Chaining (?.) and the Nullish Coalescing Operator (??), you can return a default value like so:

tabs.find((tab) => tab.current)?.name ?? "default"

CodePudding user response:

Use optional chaining operator (?.):

defaultValue={tabs.find((tab) => tab.current)?.name}

Or how about simply just using the first element:

defaultValue={tabs[0].name}

If you also want to provide a default, you can use the null coalescing operator (??)

defaultValue={tabs.find((tab) => tab.current)?.name ?? "--"}
  • Related