https://github.com/mdibyo/react-typed-context
https://github.com/mdibyo/react-typed-context
Last synced: 12 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/mdibyo/react-typed-context
- Owner: mDibyo
- Created: 2018-05-21T06:46:15.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2018-05-25T11:19:17.000Z (about 8 years ago)
- Last Synced: 2025-02-03T10:18:42.447Z (over 1 year ago)
- Language: JavaScript
- Size: 23.4 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# react-typed-context
Runtime type-checking for React Context Providers.
### Install
```
npm install --save react-typed-context
```
### Introduction
This package adds runtime type-checking of the value provided to React `Context.Provider`s by leveraging the `prop-types` package.
```js
import createContextOfType from 'react-typed-context';
import * as PropTypes from 'prop-types';
import * as React from 'react';
const CounterContext = createContextOfType(PropTypes.number.isRequired);
const Example1 = () => (
// Warning: Failed prop type: Invalid prop `value` of type `string` supplied to `PropTyped(Provider)`, expected `number`.
...
);
```
It takes an optional default value for the context.
```js
const CounterContext = createContextOfType(PropTypes.number.isRequired, 0);
const Example2 = () => (
...
{value => value} // 0
);
```
Thanks to the expressiveness of `prop-types`, arbitrarily complex values are supported.
```js
const ReadWriteThemeContext = createContextOfType(
PropTypes.shape({
theme: PropTypes.string,
setTheme: PropTypes.func.isRequired,
},
{ theme: 'dark' },
);
```