Question: React PropTypes - How to make a shape optional with its fields required?

Question

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

Answers 1
Added at 2017-09-06 20:09
Tags
Question

I have a component that receives a badge prop (see example down below). The badge is optional, but once it is used I want it to have some required fields inside it. I've tried the following:

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

It works, but I get this warning on Chrome when trying to use it without the badge:

Warning: Failed prop type: The prop badge.src is marked as required in Component, but its value is null.

What is the proper way of doing this?


Component usage example:

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


Barack Obama without flag badge not supplied

Answers to

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

nr: #1 dodano: 2017-09-08 22:09

This is the correct way to do this. I was very intrigued by how this wouldn't work, so I pasted it in a CodePen (https://codepen.io/Oblosys/pen/xLvxrd) and it works just as expected. (Open a console, and uncomment the failing one to see a prop-type error)

Something else must be going wrong in your code, and at some point you render a Component with a badge property object that has src: null. Maybe before data from an api request has arrived? With some console logging in Component and its parent, you should be able to find the culprit.

Source Show
◀ Wstecz