React PropTypes - How to make a form optional with its fields?

I have a component that gets a badge prop (see example below). The icon is optional, but as soon as it is used, I want it to have some required fields. I tried the following:

 Component.propTypes = { badge: PropTypes.shape({ src: PropTypes.string.isRequired, alt: PropTypes.string.isRequired, }), } 

This works, but I get this warning in Chrome when I try to use it without an icon:

Warning: Faulty support type: The proportion of badge.src marked as required in Component , but its value is null .

What is the right way to do this?


Component usage example:

Barack Obama with flag badge={{ src: 'usa.png', alt: 'United States' }}


Barack Obama without a flag badge not supplied

+5
source share
1 answer

This is the right way to do this. I was very intrigued by how this would not work, so I pasted it into CodePen ( https://codepen.io/Oblosys/pen/xLvxrd ) and it works just as expected (Open the console and uncomment the error so that see prop-type error)

Something else should happen in your code, and at some point you render Component with an icon property object with src: null . Maybe before the data from the api request arrives? With some logging in Component and its parent, you should find the culprit.

+1
source

Source: https://habr.com/ru/post/1271575/


All Articles