Skip to content

Detect "Functions are not valid as a React child." errors #26182

@donaldpipowitch

Description

@donaldpipowitch

Search Terms

  • "Functions are not valid as a React child."
  • "Functions are not valid as a JSX child."

Suggestion

In React it is not possible to return a function as a React child. It would be nice if TypeScript could catch this type error.

Use Cases

Sometimes you want to use a function inside an JSX expression, but if you forget to call it, it will throw on runtime.

Examples

See https://codesandbox.io/s/n3k4ooq3jj:

import * as React from "react";
import { render } from "react-dom";

const helloWorld = () => "Hello World!";

const App = () => <p>{helloWorld}</p>;
                            // ^---- should catch "Functions are not valid as a React child."
                            // ^---- {helloWorld()} would be correct

render(<App />, document.getElementById("root"));

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript / JavaScript code ❓ It could break builds for invalid code, so... 🤷‍♀️
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. new expression-level syntax)

Metadata

Metadata

Assignees

No one assigned

    Labels

    ExternalRelates to another program, environment, or user action which we cannot control.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions