ReactJS - isDOMComponent()



ReactJS is like a toolbox for web developers. It helps them build websites by breaking everything into small parts called components. Each component has its own schedule, and React provides tools that developers can use at different times while building these parts.

One of these built-in methods is the isDOMComponent() method. It checks that the given instance is a DOM component. So we can say that, it helps us in finding that a portion of our web page is a basic HTML element such as a <div> or a <span>.

Syntax

isDOMComponent(instance)

Parameters

instance − This is the instance of a React element in which we want to check out that it is a DOM component. It is the element we want to test.

Return Value

The isDOMComponent function returns either true or false as a Boolean value.

  • true − If the instance is a DOM component, such as a <div> or <span>.

  • false − If the instance is not a DOM component or is a custom React component.

Examples

Example − Check div element

Let us consider a simple example to see how isDOMComponent() works. So we will create a simple App component in which we will have a function checkIfDOMComponent(). Inside this component we are using isDOMComponent() to check if the elementToCheck is a DOM component. Then we will display the result when the button is clicked. So let us see the code −

import React from 'react';
import { isDOMComponent } from 'react-dom/test-utils';

const App = () => {
   function checkIfDOMComponent() {
      const isDOM = isDOMComponent(elementToCheck);
      console.log("Is it a DOM component? " + isDOM);
   }   
   const elementToCheck = <div>Hello, I am a div element!</div>;   
   return (
      <div>
         <h1>React App</h1>
         <button onClick={checkIfDOMComponent}>Check Component</button>
         {elementToCheck}
      </div>
   );
}

export default App;

Output

div_element

Example − Weather App

This code represents a simple React component for a weather app (Weather.js) and a respective test file (Weather.test.js) using the @testing-library/react library. The Weather component is a functional React component that uses the useState hook to manage the state of the city and temperature. The getTemperature function is simulated to fetch the temperature asynchronously, and for simplicity, it generates a random temperature. The code is as follows −

Weather.js

import React, { useState } from 'react';

function Weather() {
   const [city, setCity] = useState('');
   const [temperature, setTemperature] = useState(null);   
   const getTemperature = async () => {
      const randomTemperature = Math.floor(Math.random() * 40) + 1;      
      setTemperature(randomTemperature);
   };
   
   return (
      <div>
         <h2>Weather App</h2>
         <div>
            <label htmlFor="cityInput">Enter City:</label>
            <input
               type="text"
               id="cityInput"
               value={city}
               onChange={(e) => setCity(e.target.value)}
            />
            <button onClick={getTemperature}>Get Temperature</button>
         </div>
         {temperature !== null && (
            <p>
               The temperature in {city} is {temperature}°C.
            </p>
         )}
      </div>
   );
}

export default Weather;

Weather.test.js

import React from 'react';
import { render, fireEvent, waitFor } from '@testing-library/react';
import Weather from './Weather';

test('renders weather component and fetches temperature', async () => {
   const { getByText, getByLabelText } = render(<Weather />);
   
   const cityInput = getByLabelText(/enter city/i);
   fireEvent.change(cityInput, { target: { value: 'New York' } });
   
   const getTemperatureButton = getByText(/get temperature/i);
   fireEvent.click(getTemperatureButton);
   
   await waitFor(() => {
      const temperatureElement = getByText(/the temperature in new york/i);
      expect(temperatureElement).toBeInTheDocument();
      expect(temperatureElement).toBeInstanceOf(HTMLElement); // Using isDOMComponent()
   });
});

Output

weather app

Example − Image Gallery App

This code includes a simple React component for an image gallery (ImageGallery.js) and a corresponding test file (ImageGallery.test.js) using the @testing-library/react library. The test checks whether the ImageGallery component renders correctly by ensuring that each image element is present in the document. It utilizes the render function from @testing-library/react to create a virtual DOM for testing. The code for this app is as follows −

ImageGallery.js

import React, { useState } from 'react';

function ImageGallery() {
   const [images, setImages] = useState([
      'image1.jpg',
      'image2.jpg',
      'image3.jpg',
   ]);
   
   return (
      <div>
         <h2>Image Gallery</h2>
         <div>
            {images.map((image, index) => (
               <img key={index} src={image} alt={`Image ${index + 1}`} />
            ))}
         </div>
      </div>
   );
}

export default ImageGallery;

ImageGallery.test.js

import React from 'react';
import { render } from '@testing-library/react';
import ImageGallery from './ImageGallery';

test('renders image gallery component', () => {
   const { getByAltText } = render(<ImageGallery />);   
   for (let i = 1; i <= 3; i++) {
      const imageElement = getByAltText(`Image ${i}`);
      expect(imageElement).toBeInTheDocument();
      expect(imageElement).toBeInstanceOf(HTMLElement); // Using isDOMComponent()
   }
});

Output

image gallery

Summary

So, whenever we call isDOMComponent(instance), it will return true if the instance is a DOM component and false otherwise. This function checks whether an element is a standard HTML element or a customized React component.

reactjs_reference_api.htm
Advertisements