Is React
Determine if a variable or expression is a valid element or component in React
A library to determine if a variable or an expression is a React element or component.
For a more thorough understanding, this article describes elements and components in React, and this article
gives an understanding of the JSX syntax.
Install
yarn add is-react
or npm i --save is-react
to use the package.
Examples
Real world:
import React from 'react';
import isReact from 'is-react';
const MyImageComponent = ({ SomeProp }) => {
if (typeof SomeProp === 'string') {
return <img src={SomeProp} />;
} else if (isReact.component(SomeProp)) {
return <SomeProp />;
} else if (isReact.element(SomeProp)) {
return SomeProp;
}
return null;
};
Samples:
class Foo extends React.Component {
render() {
return <h1>Hello</h1>;
}
}
const foo = <Foo />;
function Bar(props) {
return <h1>World</h1>;
}
const bar = <Bar />;
const header = <h1>Title</h1>;
isReact.compatible(Foo);
isReact.component(Foo);
isReact.classComponent(Foo);
isReact.functionComponent(Foo);
isReact.element(Foo);
isReact.compatible(<Foo />);
isReact.component(<Foo />);
isReact.element(<Foo />);
isReact.DOMTypeElement(<Foo />);
isReact.compositeTypeElement(<Foo />);
isReact.compatible(Bar);
isReact.component(Bar);
isReact.classComponent(Bar);
isReact.functionComponent(Bar);
isReact.element(Bar);
isReact.compatible(<Bar />);
isReact.component(<Bar />);
isReact.element(<Bar />);
isReact.DOMTypeElement(<Bar />);
isReact.compositeTypeElement(<Bar />);
isReact.compatible(header);
isReact.component(header);
isReact.element(header);
isReact.DOMTypeElement(header);
isReact.compositeTypeElement(header);
API
import isReact from 'is-react'
to use the package
All functions return a boolean
. The primary functions you will most likely
use are compatible()
, element()
, and component()
.
isReact.compatible()
Determine if a variable or expression is compatible with React. Valid React
components and elements return true
.
isReact.element()
Determine if a variable or expression is a React element. Will return true
for both DOM type and Composite type components.
isReact.component()
Determine if a variable or expression is a React component. Will return true
for both functional and class components.
isReact.classComponent()
Determine if a variable or expression is a React class component.
isReact.functionComponent()
Determine if a variable or expression is a React functional component.
isReact.DOMTypeElement()
Determine if a variable or expression is a React DOM type element.
isReact.compositeTypeElement()
Determine if a variable or expression is a React Composite type element.
Thanks!
Inspired by this Stackoverflow answer