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

simple component

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

test button app

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

fetching data from api

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.

reactjs_reference_api.htm
Advertisements