facebook/prop-types

Children required prop-types fire warning on create

RobinLallier opened this issue · 5 comments

Setup

I have a Parent component taking multiple Childs beneath him:

function App() {
  const [title, setTitle] = useState(null)
  useEffect(() => fetchTitle().then(t => setTitle(t)), [])
 
  return (
    <Parent displayChildren={title}>
      <Child title={title}/>
      <Child title={title}/>
    </Parent>
  );
}

function Parent({displayChildren, children}) {
  if(displayChildren) {
     return children
  }
  return <div>Loading...</div>
}


function Child({title}) {
 // ...
}
Child.propTypes = { title: propTypes.string.isRequired }

Actual Behavior

A propTypes error is launched when App creates the Child, even though the Child are not yet rendered.

Expected Behavior

I would expect no error on title propTypes, as the component gets its title property by its first render.

Note

Here, the issue is that Child needs a title to render, so isRequired is an important information that I don't want to waste. However, it is not required on element creation. Could there be a way to specify (not sure if via react or proptypes) that I want propTypes to check the propTypes on render only?

This error comes from React, not this library.

However I'm pretty sure that propTypes fire when the element is created, not when it's rendered, so you can find the error sooner.

A better solution is to not render the Child elements at all when title is falsy.

Closing, since it's not a prop-types issue specifically.

Hi, what do you mean by "when the element is created"? The element is not even mounted in this case, why propType is checked? Have the same problem

They’ve always been checked when the element is created - which for jsx, is the moment the jsx is evaluated.

thanks for feedback

it seems that the check is needed when the component is mounted, because for a developer the component exists when it is mounted - that is the moment we can control

No, you’re not correct. You control when it’s created - react controls when it’s mounted.