skip to Main Content

Full reproducible repo is https://github.com/Liooo/vite-project, just run yarn install && yarn tsc to see the error.

I want to use react v18 with Typescript < v5.1, but tsc raises error TS2786 'MyComponent' cannot be used as a JSX component. Its return type 'string' is not a valid JSX element. like below:

const MyComponent = () => 'x'

function App() {
  return (
    <>
      <div>
        <MyComponent />
       // ↑
        // error TS2786: 'MyComponent' cannot be used as a JSX component.
        //     Its return type 'string' is not a valid JSX element.
      </div>
    </>
  )
}
// package.json
{

  "dependencies": {
    "react": "^18.3.1",
    "react-dom": "^18.3.1"
  },
  "devDependencies": {
    "@types/react": "^18.3.3",
    "@types/react-dom": "^18.3.0",
    "typescript": "4.9.5" // <= the error disappears with for example "5.1.6"
  }
}

When I update typescript to > v5.1, the error disappears.

Tried tweaking JSX.Element augmentation like these but no luck so far.

to be precise, my goal here is the following:

  1. use react@v18
  2. use [email protected]
  3. allow string (and other ReactNode-ish types) as valid JSX Element

Notes:

Wrapping strings in elements like const MyComponent = () => (<>{'x'}</>) works, but don’t wanna do this, wanna be able to return string from component)

The error should be related to this microsoft/Typescript issue

2

Answers


  1. Chosen as BEST ANSWER

  2. just run the function?
    Why try to make functional component return a string?

    const myStringfunc = (): string => { return 'x' }
    ...
    <div>{ myStringfunc() }</div>
    

    apparently I need to change function name to make it clear I’m not suggesting a FC as a solution but a regular function that returns a string. If the real use case resulted in a expensive re-render, hoist it, bind it to a const, memoize it.

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