Skip to content

@types/react Objects are not valid as a React child #34530

@christoomey

Description

@christoomey

The React typings allow passing an object as a child, but doing so results in a runtime error thrown by React with the message "Objects are not valid as a React child".

I'm guessing this is due to the wide variety of things that are valid react children, specific functions for render props, but I'm wondering if there is a way to refine the type definition to get this (passing an object as a child) to be an error.

I've unfortunately run into this a bunch when working with nested objects and accidentally not traversing deep enough into the object when trying to display data, e.g. user.address.street where street is, in fact, an object, and thus will throw an error.

The following is a minimal reproduction that demonstrates the issue, specifically in that the types permit this, rather than resulting in a compile error. Also capture in this CodeSandbox:

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

const App = () => {
  const data = { user: { name: "Chris" } };

  // The following throws a runtime error from React
  // "Objects are not valid as a React child"
  // Ideally this would be caught at compile time
  return <p>{data}</p>;
};

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions