UNPKG

2.63 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 StatelessComponent = () => 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(StatelessComponent); // 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#### ConcurrentMode
49
50```js
51import React from "react";
52import * as ReactIs from 'react-is';
53
54ReactIs.isConcurrentMode(<React.unstable_ConcurrentMode />); // true
55ReactIs.typeOf(<React.unstable_ConcurrentMode />) === ReactIs.ConcurrentMode; // true
56```
57
58#### Context
59
60```js
61import React from "react";
62import * as ReactIs from 'react-is';
63
64const ThemeContext = React.createContext("blue");
65
66ReactIs.isContextConsumer(<ThemeContext.Consumer />); // true
67ReactIs.isContextProvider(<ThemeContext.Provider />); // true
68ReactIs.typeOf(<ThemeContext.Provider />) === ReactIs.ContextProvider; // true
69ReactIs.typeOf(<ThemeContext.Consumer />) === ReactIs.ContextConsumer; // true
70```
71
72#### Element
73
74```js
75import React from "react";
76import * as ReactIs from 'react-is';
77
78ReactIs.isElement(<div />); // true
79ReactIs.typeOf(<div />) === ReactIs.Element; // true
80```
81
82#### Fragment
83
84```js
85import React from "react";
86import * as ReactIs from 'react-is';
87
88ReactIs.isFragment(<></>); // true
89ReactIs.typeOf(<></>) === ReactIs.Fragment; // true
90```
91
92#### Portal
93
94```js
95import React from "react";
96import ReactDOM from "react-dom";
97import * as ReactIs from 'react-is';
98
99const div = document.createElement("div");
100const portal = ReactDOM.createPortal(<div />, div);
101
102ReactIs.isPortal(portal); // true
103ReactIs.typeOf(portal) === ReactIs.Portal; // true
104```
105
106#### StrictMode
107
108```js
109import React from "react";
110import * as ReactIs from 'react-is';
111
112ReactIs.isStrictMode(<React.StrictMode />); // true
113ReactIs.typeOf(<React.StrictMode />) === ReactIs.StrictMode; // true
114```