Search code examples
reactjsreact-proptypes

Should React component's not required prop be inside defaultProps


First of all, I've already checked React's documentation and didn't find answer to my question. I did the same here on SO without any success.

The question is: If a prop that is being used in React's component is not required, should it be in the defaultProps?

  Component.propTypes = {
    getName: PropTypes.func,
    type: PropTypes.string.isRequired,
  };

  static defaultProps = {
    type: 'text',
    getName: () => {}, // should this be here at all ?!?
  };

I am asking this because there are no errors in console if I put it here or if I don't. The thing is, I saw on some projects that people are using defaultProps to supply the component with some fallback value, while on other projects I worked on, in defaultProps, people put the fallback values only for the fields that have isRequired property in order to avoid rendering errors or console errors if they don't pass that prop to the component.


Solution

  • If that function is passed to some event i.e.

    <button onClick={props.callback} />
    

    if i'll do this and sometimes onClick is not required at all(like just we want to show button no click actions). that time we won't pass it and if someone clicks we will get error undefined is not a function because callback is undefined

    For solving that issue what we will do is

    <button onClick={() => props.callback && props.callback()} />
    

    But this is not efficient because on each render one new function will get created and that is not good practice.

    next way is

    function Button(props) {
        <button onClick={props.callback} />
    }
    props.defaultProps = {
        callback: () => {} // that will fallback if is not passed.
    }
    
    

    this will handle fallback and looks clean as well and batter way to do it.

    and if we mark that prop as required then anyhow eslint will throw this error