ReactJS - findRenderedComponentWithType()



There is a function in React.js called findRenderedComponentWithType(). This function is like another function called scryRenderedComponentsWithType(), but it works differently. The basic idea behind findRenderedComponentWithType() is to locate and return a given component in a rendered tree.

The goal of findRenderedComponentWithType() is to search for a given component within a rendered tree (a structure of React components). When compared to several other functions, findRenderedComponentWithType() requires only one match. If there are several matches or no matches at all, an exception will be thrown.

Syntax

findRenderedComponentWithType(tree, componentClass)

Parameters

tree − This is the rendered tree of React components in which we want to search.

componentClass − This is the type of component we want is given by its class.

Return Value

findRenderedComponentWithType() returns the single React component within the rendered tree that matches the given class type. If there is just one match, it will return that component. If there is no match or more than one match, it will throw an exception, indicating that there is a problem with the expected number of matches.

Examples

Example − Counter App and Testing

This is the basic counter app in which we will have a button which is used to increment the counter. And then we will create testing for this component to test its functionality. So let us see the code for both app and testing −

CounterApp.js

import React, { useState } from 'react';

const CounterApp = () => {
   const [count, setCount] = useState(0);   
   const increment = () => {
      setCount(count + 1);
   };
   
   return (
      <div>
         <h1>Counter App</h1>
         <p>Count: {count}</p>
         <button onClick={increment}>Increment</button>
      </div>
   );
};

export default CounterApp;

CounterApp.test.js

import React from 'react';
import { render } from '@testing-library/react';
import { findRenderedComponentWithType } from 'react-dom/test-utils';
import CounterApp from './CounterApp';

test('finds and interacts with the "Increment" button', () => {
   const { container } = render(<CounterApp />);
   const incrementButton = findRenderedComponentWithType(container, HTMLButtonElement);
   
   // The testing logic goes here
   expect(incrementButton.textContent).toBe('Increment');
   // Additional assertions
});

Output

counter app increment 1

Example − Email validation App and Testing

Now we will create a small application in which will verify email address of user and create testing code using the findRenderedComponentWithType() method −

FormValidationApp.js

import React, { useState } from 'react';

const FormValidationApp = () => {
   const [email, setEmail] = useState('');
   const [validEmail, setValidEmail] = useState(false);   
   const handleEmailChange = (e) => {
      const newEmail = e.target.value;
      setEmail(newEmail);
      setValidEmail(validateEmail(newEmail));
   };
   
   const validateEmail = (input) => {
      
      // Simple email validation logic
      return /\S+@\S+\.\S+/.test(input);
   };
   
   return (
      <div>
         <h1>Form Validation App</h1>
         <label>Email:</label>
         <input type="text" value={email} onChange={handleEmailChange} />
         {validEmail ? <p>Email is valid!</p> : <p>Email is not valid.</p>}
      </div>
   );
};

export default FormValidationApp;

FormValidationApp.test.js

import React from 'react';
import { render } from '@testing-library/react';
import { findRenderedComponentWithType } from 'react-dom/test-utils';
import FormValidationApp from './FormValidationApp';

test('finds and validates the email input', () => {
   const { container } = render(<FormValidationApp />);
   const emailInput = findRenderedComponentWithType(container, HTMLInputElement);
   
   //testing logic
   expect(emailInput.type).toBe('text');
});

Output

form validation app email

Example − Toggle Switch App and Testing

In this app we will use toggle functionality in which we have on and off functionality and then we will create testing for this functionality using findRenderedComponentWithType(). So for this app and test code is as follows −

ToggleSwitchApp.js

import React, { useState } from 'react';

const ToggleSwitchApp = () => {
   const [isOn, setIsOn] = useState(false);
   
   const toggleSwitch = () => {
      setIsOn(!isOn);
   };
   
   return (
      <div>
         <h1>Toggle Switch App</h1>
         <label>
            <input type="checkbox" checked={isOn} onChange={toggleSwitch} />
            {isOn ? 'ON' : 'OFF'}
         </label>
      </div>
   );
};

export default ToggleSwitchApp;

ToggleSwitchApp.test.js

import React from 'react';
import { render } from '@testing-library/react';
import { findRenderedComponentWithType } from 'react-dom/test-utils';
import ToggleSwitchApp from './ToggleSwitchApp';

test('finds and interacts with the toggle switch', () => {
   const { container } = render(<ToggleSwitchApp />);
   const toggleSwitch = findRenderedComponentWithType(container, HTMLInputElement);
   
   // testing logic 
   expect(toggleSwitch.type).toBe('checkbox');
});

Output

switch on switch off

Summary

In this tutorial, we have learned about findRenderedComponentWithType(), a React.js function that helps in locating a specific component in a rendered tree. We analyzed its parameters and then used this knowledge to create three different React.js apps. We have not only understood the concept, but we have also put it into practice, making our learning more hands-on.

reactjs_reference_api.htm
Advertisements