简体   繁体   中英

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.

If that function is passed to some event ie

<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

Missing defaultProps will not cause any error. It's more like a good practice. Keeping defaultProps for all the props for a component will reduce the chance of app crash if the component is not receiving a prop which it is expecting. If that scenario is not handled properly, defaultProps does help. And from a developer point of view by looking at propTypes and defaultProps of a component, the developer will understand what type and value, it's expecting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM