Skip to content

Instantly share code, notes, and snippets.

@brillout
Last active February 22, 2024 12:44
Show Gist options
  • Save brillout/c27b780f009d141acec7bda29d136e6e to your computer and use it in GitHub Desktop.
Save brillout/c27b780f009d141acec7bda29d136e6e to your computer and use it in GitHub Desktop.
React patch (component trace)

The problem

Before throwing the error Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) React usually logs a component trace:

Check your code at +Page.tsx:26.
    at Page
    at div
    at div
    at Layout (/pages/+Layout.tsx:66:19)

Note

You can see an example of such component trace here.

But it sometimes doesn't, which makes finding the problematic React component very hard. To get a component trace, you can use the temporary patch down below.

Also, the component trace can be incomplete. For example, the component trace above says Check your code at +Page.tsx:26 but there can be hundreds of +Page.tsx files and it doesn't say which +Page.tsx file it is. If it's an issue, then you can use the temporary patch down below.

The patch

The following patch provides a systematic and precise component trace.

// node_modules/react/cjs/react.production.min.js

// ...

// Insert this at this end of the file
exports.createElement = debugEl(exports.createElement);
function debugEl(fn) {
  return (...args) => {
    const el = args[0];
    if (typeof el === 'object' && !el.$$typeof && !el.getModuleId) {
      console.error('Error: INVALID REACT ELEMENT:');
      console.error(el);
      console.error(new Error('INVALID REACT ELEMENT, ORIGIN:'));
      globalThis.process?.exit?.(1);
    }
    return fn(...args);
  }
}
// node_modules/react/cjs/react-jsx-runtime.production.min.js

// ...

// Insert this at this end of the file
exports.jsx = debugEl(exports.jsx);
function debugEl(fn) {
  return (...args) => {
    const el = args[0];
    if (typeof el === 'object' && !el.$$typeof && !el.getModuleId) {
      console.error('Error: INVALID REACT ELEMENT:');
      console.error(el);
      console.error(new Error('INVALID REACT ELEMENT, ORIGIN:'));
      globalThis.process?.exit?.(1);
    }
    return fn(...args);
  }
}

Note

This patch works with React 18.2.0 (and probably with most other React versions). Let the Vike team know if it doesn't work with your React version.

The debug logs will help you find which React component is undefined (or an object).

Once you fixed the problem, you can remove the patch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment