skip to Main Content

I am new to writing typescript with react, and the first error I encountered is when I return a string from a component, I don’t think this is invalid because react knows how to deal with it:

function MyComponent(){
  const Test = ()=> "Hello" 
  return <Test />
}

Typescript complains:

‘Test’ cannot be used as a JSX component. Its return type ‘string’
is not a valid JSX element.

You might say, wrap it in a React fragment.

Although wrapping it in a React fragment works, it’s not always cool, take the following example:

import type { PropsWithChildren } from 'react'

interface P extends PropsWithChildren {}

function MyComponent() {
  const Button = (props: P) => {
    const { children } = props
    return children
  }
  return <Button>Hello world</Button>
}

Typescript complains:

‘Button’ cannot be used as a JSX component. Its return type
‘ReactNode’ is not a valid JSX element.
Type ‘undefined’ is not assignable to type ‘Element | null’

Now in order to get around this I will have to write:

return (
  <Button>
    <React.Fragment>
      Hello world
    </React.Fragment>
  </Button>
)

Is there a way to make this error not get into my way?

2

Answers


  1. Typescript is not recognizing your Test as a component because the typing is not explicitly defined. To distinguish a regular function from a React component, You can either assign a component type such as React.FC or assign a return type of React.ReactNode to it.

    Login or Signup to reply.
  2. If your are trying to return and represent a component using React with TypeScript, you need to return a JSX component (as you have already verified, wrapping it with a fragment).

    You can see more details in this answer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search