- ReactJS Tutorial
- ReactJS - Home
- ReactJS - Introduction
- ReactJS - Installation
- ReactJS - Features
- ReactJS - Advantages & Disadvantages
- ReactJS - Architecture
- ReactJS - Creating a React Application
- ReactJS - JSX
- ReactJS - Components
- ReactJS - Nested Components
- ReactJS - Using Newly Created Components
- ReactJS - Component Collection
- ReactJS - Styling
- ReactJS - Properties (props)
- ReactJS - Creating Components using Properties
- ReactJS - props Validation
- ReactJS - Constructor
- ReactJS - Component Life Cycle
- ReactJS - Event management
- ReactJS - Creating an Event−Aware Component
- ReactJS - Introduce Events in Expense Manager APP
- ReactJS - State Management
- ReactJS - State Management API
- ReactJS - Stateless Component
- ReactJS - State Management Using React Hooks
- ReactJS - Component Life Cycle Using React Hooks
- ReactJS - Layout Component
- ReactJS - Pagination
- ReactJS - Material UI
- ReactJS - Http client programming
- ReactJS - Form Programming
- ReactJS - Controlled Component
- ReactJS - Uncontrolled Component
- ReactJS - Formik
- ReactJS - Conditional Rendering
- ReactJS - Lists
- ReactJS - Keys
- ReactJS - Routing
- ReactJS - Redux
- ReactJS - Animation
- ReactJS - Bootstrap
- ReactJS - Map
- ReactJS - Table
- ReactJS - Managing State Using Flux
- ReactJS - Testing
- ReactJS - CLI Commands
- ReactJS - Building and Deployment
- ReactJS - Example
- Hooks
- ReactJS - Introduction to Hooks
- ReactJS - Using useState
- ReactJS - Using useEffect
- ReactJS - Using useContext
- ReactJS - Using useRef
- ReactJS - Using useReducer
- ReactJS - Using useCallback
- ReactJS - Using useMemo
- ReactJS - Custom Hooks
- ReactJS Advanced
- ReactJS - Accessibility
- ReactJS - Code Splitting
- ReactJS - Context
- ReactJS - Error Boundaries
- ReactJS - Forwarding Refs
- ReactJS - Fragments
- ReactJS - Higher Order Components
- ReactJS - Integrating With Other Libraries
- ReactJS - Optimizing Performance
- ReactJS - Profiler API
- ReactJS - Portals
- ReactJS - React Without ES6 ECMAScript
- ReactJS - React Without JSX
- ReactJS - Reconciliation
- ReactJS - Refs and the DOM
- ReactJS - Render Props
- ReactJS - Static Type Checking
- ReactJS - Strict Mode
- ReactJS - Web Components
- Additional Concepts
- ReactJS - Date Picker
- ReactJS - Helmet
- ReactJS - Inline Style
- ReactJS - PropTypes
- ReactJS - BrowserRouter
- ReactJS - DOM
- ReactJS - Carousel
- ReactJS - Icons
- ReactJS - Form Components
- ReactJS - Reference API
- ReactJS Useful Resources
- ReactJS - Quick Guide
- ReactJS - Useful Resources
- ReactJS - Discussion
ReactJS - isCompositeComponentWithType()
As we know that in React each component has its own life cycle, which means that they progress via different stages while operating in our project. React provides built-in methods for controlling these processes.
So let's have a look at the isCompositeComponentWithType() method now. This method tells us whether a given element of our program is a React component. Here's how we can put it to use −
Syntax
isCompositeComponentWithType( instance, componentClass )
Parameters
In React, the isCompositeComponentWithType method needs two parameters −
instance − This argument provides a component instance that we want to test.
componentClass − A React component class is represented by this parameter.
Return Value
The function will determine whether or not the instance is an instance of this component class. The function produces a boolean result −
If the instance is a component whose type matches the componentClass, it returns true.
If the instance is not a component of the supplied componentClass, it returns false.
Examples
Example − Simple App
Let us create a simple React app with a component and then use isCompositeComponentWithType() in a test. We will have a simple React component (MyComponent) and a test code. The test uses isCompositeComponentWithType() to check if the rendered component is a composite component of type "div." The code for this app is as follows −
MyComponent.js
import React from 'react'; import { render } from '@testing-library/react'; import { isCompositeComponentWithType } from 'react-dom/test-utils'; const MyComponent = () => { return ( <div> <h1>Hello, I'm a simple component!</h1> </div> ); }; export default MyComponent; test('MyComponent is a composite component of type "div"', () => { const { container } = render(<MyComponent />); const isComposite = isCompositeComponentWithType(container.firstChild, 'div'); expect(isComposite).toBe(true); });
Output
Example − Test Button App
Here is the complete code for an App.js file that includes the isCompositeComponentWithType() method to show the usage of the method.
import React from 'react'; import { isCompositeComponentWithType } from 'react-dom/test-utils'; // Define App Component const App = () => { // Function to show isCompositeComponentWithType() function myFunction() { var a = isCompositeComponentWithType(el); console.log("Is the following element a composite component? " + a); } // The element for testing const el = <div> <h1>element</h1> </div> // Return the user interface return ( <div id='el'> <h1>React isCompositeComponentWithType() method usage</h1> <button onClick={myFunction}> Click Me !! </button> </div> ); } export default App;
Output
This code shows an App component that is having a function myFunction to show the isCompositeComponentWithType() method. When we click the button in our app, it will check if the el element is a composite component and log the result.
Let us say we are creating a digital storefront and want to know if a specific section of our website is a type of product listing. We can accomplish this by calling the isCompositeComponentWithType() function. First, we import the required tools, build a function to verify, create an element (the product listing), and then display it on our website with a test button.
Example − Fetching Data from an API
Now we will have an app fetching and displaying data from an API. And also the test file which uses isCompositeComponentWithType() to test if the FetchData component renders the data fetched from the API. It uses the render function from @testing-library/react to render the component, and waitFor to wait for the asynchronous fetch call to complete. The code for this app is as follows −
// FetchData.js import React, { useState, useEffect } from 'react'; const FetchData = () => { const [data, setData] = useState([]); useEffect(() => { const fetchData = async () => { try { const response = await fetch('https://jsonplaceholder.typicode.com/todos'); const result = await response.json(); setData(result); } catch (error) { console.error('Error fetching data:', error); } }; fetchData(); }, []); return ( <div> <h1>Fetching Data from an API</h1> <ul> {data.map(item => ( <li key={item.id}>{item.title}</li> ))} </ul> </div> ); }; export default FetchData;
FetchData.test.js
import React from 'react'; import { render, waitFor } from '@testing-library/react'; import FetchData from './FetchData'; // fetch function global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve([{ id: 1, title: 'Sample Todo' }]), }) ); test('FetchData renders data from API', async () => { const { getByText } = render(<FetchData />); // Wait for the fetch call await waitFor(() => expect(fetch).toHaveBeenCalledTimes(1)); const todoItem = getByText('Sample Todo'); expect(todoItem).toBeInTheDocument(); });
Output
Summary
isCompositeComponentWithType() is a useful tool to identify the type of React components in our application and check their validity in a testing or debugging situation. We have created three different apps to showcase the usage of this function.
To Continue Learning Please Login
Login with Google