Search code examples
reactjstypescriptfunctionreact-propsdangerouslysetinnerhtml

Type '() => Element' is not assignable to type 'string'


Grettings !

I have a conventional function and I'm returning a span with a prop(if I'm not wrong). On my ts code I have this error

Error image

Here's my code.The file name is qCard.tsx

import { QuestionAnswerTwoTone } from "@material-ui/icons";
import React from "react";

// crear props
type Props = {
  question: string;
  answers: string[];
  callback: any;
  userAnswer: boolean;
  questionNm: number;
  totalQuestions: number;
};

// A function statement declared component that takes no children.
export default function QuestionCard({
  question,
  answers,
  callback,
  userAnswer,
  questionNm,
  totalQuestions,
}: Props) {
  //duda
  return (<div>
      <p> Question :  {questionNm} / {totalQuestions} </p>
      <p dangerouslySetInnerHTML={{ __html: question }} />
      <div>
          {answers.map(function answer(){
              return(  <div>
                <button disabled={userAnswer} onClick={callback}>
                    <span dangerouslySetInnerHTML={{ __html: answer }}/>
                </button>
            </div>);
          } )}
      </div>

  </div>
    
        );
}

(Error line)

I have tried to remove {{ **__html**: answer }} leaving it like : {{ answer }} but it doesn't work.


Solution

  • This is because, you are using the function name (an element in React) for __html:

    answers.map(function answer(){
     //    __html: answer ^^
    

    Use arrow function instead:

    answers.map(answer => {
      // __html: answer // now it works.
    

    Or, if you wish to continue using function statement then you can pass a parameter and use:

    answers.map(function answer(ans){
      // __html: ans