React warns about the passed support with the value null, where PropType is not required for the propeller

I have a component that accepts an error as a string or object with 2 required properties. But null can also be passed for this support. In my current installation, React throws a warning when passing null :

Warning: Faulty support type: Invalid prop error specified in ErrorDialog

What should I change for React to allow null | string | an object with this shape ? Thanks!

 ErrorDialog.propTypes = { onResetError: PropTypes.func.isRequired, error: PropTypes.oneOfType([ PropTypes.shape({ id: PropTypes.number.isRequired, defaultMessage: PropTypes.string.isRequired, }), PropTypes.string, ]), }; 

Full code:

 import React, { PropTypes } from 'react'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import { FormattedMessage } from 'react-intl'; const ErrorDialog = ({ error, onResetError }) => { function renderError() { if (!error) { return null; } else if (typeof error === 'string') { return error; } else if (typeof error === 'object') { return <FormattedMessage {...error} />; } return null; } return ( <Dialog modal={false} open={Boolean(error)} actions={ <FlatButton label="OK" primary onTouchTap={onResetError} /> } > {renderError()} </Dialog> ); }; ErrorDialog.propTypes = { onResetError: PropTypes.func.isRequired, error: PropTypes.oneOfType([ PropTypes.shape({ id: PropTypes.number.isRequired, defaultMessage: PropTypes.string.isRequired, }), PropTypes.string, ]), }; export default ErrorDialog; 

I want to hide the dialog when there is no error, show the source line if the error has a type string and displays the translated message if the message descriptor is specified.

UPDATE: I went with this solution:

 ErrorDialog.propTypes = { onResetError: PropTypes.func.isRequired, // eslint-disable-next-line consistent-return error(props, propName, componentName) { const prop = props[propName]; if (prop !== null && typeof prop !== 'string' && !(typeof prop === 'object' && prop.id && prop.defaultMessage)) { return new Error( `Invalid prop \`${propName}\` supplied to ${componentName}. Validation failed.` ); } }, }; 
+8
javascript reactjs
source share
1 answer

Read this issue and this issue for discussion in the past. Just make props.error optional and check the value in the code. Otherwise, you will need to implement your own verification confirmation .

From the docs:

 // You can also specify a custom validator. It should return an Error // object if the validation fails. Don't `console.warn` or throw, as this // won't work inside `oneOfType`. customProp: function(props, propName, componentName) { if (!/matchme/.test(props[propName])) { return new Error( 'Invalid prop `' + propName + '` supplied to' + ' `' + componentName + '`. Validation failed.' ); } } 
+5
source share

All Articles