At present, if propType
validation fails, ReactJS uses console.warn
to emit a warning. I really, really want a real error in dev mode, so it can fail our continuous integration build, instead of just printing a message that might be lost in the shuffle.
There's already been discussion of this, e.g. in this feature request, and this related question describes the current behavior as expected. That's fine, but I personally want it to throw an error.
Assuming that ReactJS doesn't provide better support for this any time soon, what's the best workaround? So far, the best I've come up with is to override console.warn
for tests, e.g.
console.warn = function(msg) { throw new Error(msg); };
The downside of this is, it can be tricky to implement in tests, and it's not React-specific, so other console.warn
calls also need to be handled.
With the new feature in React, developers can test the Error Boundaries by a toggle error button, added to the DevTools. When we click on the toggle error button on the component labeled 'Inner Component', Error boundary is triggered.
import { useState } from "react"; const App = () => { const [error, setError] = useState(Error()); const throwError = () => { throw Error("I'm an error"); }; const crash = () => { try { throwError(); } catch (e) { setError(e); console.
PropTypes is deprecated since React 15.5.
One of the most important things when building React application is to make sure that the components receive correct props. Passing wrong props leads to bugs and unexpected behavior, so it's a good idea to warn developers about this as early as possible.
From this answer, you can check the error message against typical react messages and only throw for those. Not perfect, but maybe a step closer to what you're looking for:
let warn = console.warn; console.warn = function(warning) { if (/(Invalid prop|Failed propType)/.test(warning)) { throw new Error(warning); } warn.apply(console, arguments); };
FlowType, introduced by Facebook yesterday sounds like exactly what you're after. It can analyse your code, infer types, and throw errors at compile time.
It specifically includes support for React and the propTypes argument: https://flow.org/en/docs/react/components/
Update (July 21) - Link above fixed, but given Facebook's recent change on Flow to heavily prioritise internal use over future community use, would recommend TypeScript instead for new projects. Example:
https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/class_components/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With