React Element Selector Query (RESQ)

1.11.0 · active · verified Sun Apr 19

resq (React Element Selector Query) is a JavaScript library designed to query React components and HTML elements within the React Virtual DOM, emulating the functionality of `querySelector` and `querySelectorAll` for native DOM elements. It provides `resq$` for selecting a single matching component and `resq$$` for selecting multiple matches, supporting advanced features like wildcard selector patterns, asynchronous waiting for React to initialize, and filtering results by component state or props. The library is currently stable at version 1.11.0 and requires React v16 or higher. Its primary use cases include automated testing, debugging, and advanced component introspection in client-side React applications. It offers a programmatic interface to the React component tree, allowing developers to access internal component data like props and state through its `RESQNode` return structure.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to install `resq`, render a basic React application, and then use `resq$` and `resq$$` to select components from the rendered tree, including waiting for React to load.

import { resq$, waitToLoadReact } from 'resq';
import React from 'react';
import ReactDOM from 'react-dom';

// A simple React component for demonstration
const MyComponent = () => (
    <div data-testid="my-component">Hello from MyComponent</div>
);

// Another component
const AnotherComponent = () => (
    <p>Another one</p>
)

// The main application component
const App = () => (
    <div>
        <MyComponent />
        <AnotherComponent />
    </div>
);

// Render the application to the DOM
const rootElement = document.createElement('div');
rootElement.id = 'root';
document.body.appendChild(rootElement);
ReactDOM.render(<App />, rootElement);

async function queryComponents() {
    try {
        // Wait for React to load, then query for 'MyComponent'
        await waitToLoadReact(1000); // Wait up to 1 second

        const myComponentNode = resq$('MyComponent');
        if (myComponentNode) {
            console.log('Found MyComponent:', myComponentNode.name, myComponentNode.node.outerHTML);
            console.log('MyComponent props:', myComponentNode.props);
        } else {
            console.log('MyComponent not found after waiting.');
        }

        // Query for multiple components using a wildcard
        const allMyComponents = resq$$('My*');
        console.log('\nFound all My* components (count:', allMyComponents.length, '):');
        allMyComponents.forEach(comp => console.log('- ' + comp.name));

    } catch (error) {
        console.error('An error occurred during resq query:', error);
    }
}

queryComponents();

view raw JSON →