UNPKG

2.38 kBMarkdownView Raw
1# `react-is`
2
3This package allows you to test arbitrary values and see if they're a particular React element type.
4
5## Installation
6
7```sh
8# Yarn
9yarn add react-is
10
11# NPM
12npm install react-is
13```
14
15## Usage
16
17### Determining if a Component is Valid
18
19```js
20import React from "react";
21import * as ReactIs from "react-is";
22
23class ClassComponent extends React.Component {
24 render() {
25 return React.createElement("div");
26 }
27}
28
29const FunctionComponent = () => React.createElement("div");
30
31const ForwardRefComponent = React.forwardRef((props, ref) =>
32 React.createElement(Component, { forwardedRef: ref, ...props })
33);
34
35const Context = React.createContext(false);
36
37ReactIs.isValidElementType("div"); // true
38ReactIs.isValidElementType(ClassComponent); // true
39ReactIs.isValidElementType(FunctionComponent); // true
40ReactIs.isValidElementType(ForwardRefComponent); // true
41ReactIs.isValidElementType(Context.Provider); // true
42ReactIs.isValidElementType(Context.Consumer); // true
43ReactIs.isValidElementType(React.createFactory("div")); // true
44```
45
46### Determining an Element's Type
47
48#### Context
49
50```js
51import React from "react";
52import * as ReactIs from 'react-is';
53
54const ThemeContext = React.createContext("blue");
55
56ReactIs.isContextConsumer(<ThemeContext.Consumer />); // true
57ReactIs.isContextProvider(<ThemeContext.Provider />); // true
58ReactIs.typeOf(<ThemeContext.Provider />) === ReactIs.ContextProvider; // true
59ReactIs.typeOf(<ThemeContext.Consumer />) === ReactIs.ContextConsumer; // true
60```
61
62#### Element
63
64```js
65import React from "react";
66import * as ReactIs from 'react-is';
67
68ReactIs.isElement(<div />); // true
69ReactIs.typeOf(<div />) === ReactIs.Element; // true
70```
71
72#### Fragment
73
74```js
75import React from "react";
76import * as ReactIs from 'react-is';
77
78ReactIs.isFragment(<></>); // true
79ReactIs.typeOf(<></>) === ReactIs.Fragment; // true
80```
81
82#### Portal
83
84```js
85import React from "react";
86import ReactDOM from "react-dom";
87import * as ReactIs from 'react-is';
88
89const div = document.createElement("div");
90const portal = ReactDOM.createPortal(<div />, div);
91
92ReactIs.isPortal(portal); // true
93ReactIs.typeOf(portal) === ReactIs.Portal; // true
94```
95
96#### StrictMode
97
98```js
99import React from "react";
100import * as ReactIs from 'react-is';
101
102ReactIs.isStrictMode(<React.StrictMode />); // true
103ReactIs.typeOf(<React.StrictMode />) === ReactIs.StrictMode; // true
104```