Home > OS >  How to use a if statement returning a string in Tooltip's title pro
How to use a if statement returning a string in Tooltip's title pro

Time:02-27

im trying to conditionally provide the title of the tooltip by calling a function and using the if statement, but im having an error.

  const getStatusMessage = (answer: AnswerStatus) => {
if (answer == AnswerStatus.ANSWER_SUBMITTED || answer == AnswerStatus.ANSWER_PROCESSING) {
  return 'answers are still being processed.'
} else if (answer == AnswerStatus.QUESTION_SERVED) {
  return "question was given to candidate but didn't answer it."
} else if (answer == AnswerStatus.ANSWER_FAILED) {
  return 'there was a problem processing the answer of the candidate.'
}

}

<Tooltip placement='bottom-end' title={getStatusMessage(answer.status)}><button/></Tooltip>

---ERROR MSG---

Type 'string | undefined' is not assignable to type 'boolean | ReactChild | ReactFragment | ReactPortal'.

Type 'undefined' is not assignable to type 'boolean | ReactChild | ReactFragment | ReactPortal'.ts(2322) Tooltip.d.ts(163, 3): The expected type comes from property 'title' which is declared here on type 'IntrinsicAttributes & TooltipProps'

CodePudding user response:

The error is thrown because Tooltip component's title prop is getting value undefined

You didnt cover the default case when answer.status is undefined.

So either

<Tooltip placement='bottom-end' title={answer.status? getStatusMessage(answer.status) : '' }><button/></Tooltip>

or a return ''; statement in your getStatusMessage will do.

  const getStatusMessage = (answer: AnswerStatus) => {
if (answer == AnswerStatus.ANSWER_SUBMITTED || answer == AnswerStatus.ANSWER_PROCESSING) {
  return 'answers are still being processed.'
} else if (answer == AnswerStatus.QUESTION_SERVED) {
  return "question was given to candidate but didn't answer it."
} else if (answer == AnswerStatus.ANSWER_FAILED) {
  return 'there was a problem processing the answer of the candidate.'
}
return '';
  • Related