mohsen shabanian
mohsen shabanian

Reputation: 33

define function with html output in React with Typescript

I want to define class in React with Typescript which has a method with html output. but get error about output type of function.

interface StateProps {
  page: string,
}
class App extends React.Component<StateProps,any> {
render() {
    return (
      <div className="App">
        {this.pageContent(this.props.page)}
      </div>
    );
}
pageContent = (page:string) => {
    switch (page) {
      case "newPage":
         return <NewPage />;

      case "otherPage":
         return <OtherPage />;

      default:
        break;
    }
  }
}

error was: Type 'void' is not assignable to type 'ReactNode'.

eslint suggest use DetailedHTMLProps<HtmlAttributes<HTMLDivElement>,HTMLDivElement> but it didnt work.

Upvotes: 2

Views: 5729

Answers (1)

Esben Andersen
Esben Andersen

Reputation: 823

if you have @types/react in your package.json you should be able to do

pageContent = (page:string): ReactNode | null => { 
  ... 
}

You probable want to return null instead of breaking. Typescript doesn't like types with optional return.

Upvotes: 5

Related Questions