Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use React's context without PropTypes?

Tags:

reactjs

A project I'm working on recently moved to TypeScript, rendering React's PropTypes superfluous, except for specifying contextTypes. Now we're in the process of upgrading to a React version past 15.5, where PropTypes were moved to a separate package than react. Since our use of PropTypes is so limited, it seems unnecessary to add the prop-types dependency if there is a way to use React's context without them?

like image 926
ahstro Avatar asked Aug 31 '17 10:08

ahstro


1 Answers

Just having the key on the contextTypes object seems to work fine (assuming it uses hasOwnProperty under the hood), but for it to not log any errors, a function that returns null seems to be necessary. This works for both contextTypes as well as childContextTypes.

static contextTypes = {
  router: () => null
};

static childContextTypes = {
  location: () => null
};

getChildContext() {
  return { location: this.props.location };
}

In some instances, TypeScript complains that () => null doesn't have a property isRequired. I solved this by creating the helper function fakePropType:

const fakePropType: any = () => null
fakeProptype.isRequired = () => null
like image 189
ahstro Avatar answered Oct 18 '22 08:10

ahstro