Skip to content

React.ReactNode allows passing {} as children which will crash at runtime #357

Closed
@pomle

Description

@pomle

In https://github.com/typescript-cheatsheets/react#useful-react-prop-type-examples it says

export declare interface AppProps {
  children: React.ReactNode; // best, accepts everything
}

ReactNode produces a false positive type check for {}.

React version: 16.14

Steps To Reproduce

  1. Create a new CRA project with TypeScript using for example yarn create react-app repro --template typescript
  2. Accept a prop using React.ReactNode as type in default App component.
import React from 'react';

type AppProps = {
  children: React.ReactNode;
}

function App({children}: AppProps) {
  return <div>{children}</div>;
}

export default App;
  1. Update index.tsx and supply {} as children to ```
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <App>{{}}</App>
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

The current behavior

Application crash at runtime with the error "Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead."

Screenshot 2020-10-20 at 19 17 56

The expected behavior

The error should have been detected at compile time.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions