TS2786 – X cannot be used as a JSX component + unreachable code

Problem

You’re running into the following two symptoms:

  • Compiler error TS2786: ‘ComponentName’ cannot be used as a JSX component. Its return type ‘void’ is not a valid JSX element.
  • VS Code is showing you an “Unreachable code” message (and is unhelpfully showing you the option to “Remove unreachable code”).

You unintentionally have a void return in the component that it’s complaining about.

Solution

In JS, when you have a return on its own line followed by an expression, it gets translated into a void return. Here’s an example of code that would produce the symptoms (TS2786 + unreachable code):

export default function MovieList(props: moviesListProp){
    return 
    <GenericList>
            <div>
                <span>Movie Stuff</span>    
            </div>
    </GenericList>
}
Code language: JavaScript (javascript)

To fix this, wrap your expression with parentheses, like this:

export default function MovieListAsyncWithGenericList(props: moviesListProp){
    return (
    <GenericList list={props.movies}>
            <div>
                <span>...Movie Stuff...</span>    
            </div>
    </GenericList>)
}
Code language: JavaScript (javascript)

Alternatively, you can wrap the expression with a React fragment starting on the return line (i.e. return <>).

If you have a one-liner, then pull it up to the return line (i.e. return <Simple />). No need to wrap it.

Technically you can start the expression itself on the return line (i.e. return <GenericList…>), but I don’t suggest doing that. It results in asymmetrical formatting (and then you’ll run into strange errors when you inevitably try to line it up).