Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way of defining optional propTypes in react?

I have an optional propType

static defaultProps = {
   onSort: undefined, // undefined | () => {}
}

If undefined, we will check for undefined before the function is called.

_handleSort = () => {
   this.props.onSort && this.props.onSort()
}

So, how do I handle the propType of type Function | undefined. Should I check for undefined before calling the function or define a default function () => {}

like image 830
bhb Avatar asked Feb 08 '18 09:02

bhb


Video Answer


2 Answers

This issue suggests defining a default function as you have indicated above: https://github.com/yannickcr/eslint-plugin-react/issues/1067

Cmp.defaultProps = {
    onChange: () => {}
}

However, I am still trying to get this to work. I'd be interested if you have any luck.

like image 30
rkralston Avatar answered Oct 13 '22 01:10

rkralston


static propTypes = {
  onSort: PropTypes.oneOfType([
    PropTypes.func,
    PropTypes.any
  ])
}

Then check if onSort exist.

if (this.props.onSort) {
  //do something
}

OR

Define the propTypes like this:

static propTypes = {
  onSort: PropTypes.func
}

then have a default for onSort like so:

static defaultProps = {
   onSort: () => null
}
like image 181
codejockie Avatar answered Oct 13 '22 03:10

codejockie