/data-hooks

Primary LanguageTypeScriptMIT LicenseMIT

Typed Data Hooks Generator

Data-hook is a string passed to HTML Element data-hook attribute.

Use the data-hook attribute to find elements by the string.

@wix/data-hooks is a generator of data-hooks strings to share them between components, drivers and tests

Install

npm install @wix/data-hooks

# To use `withDataHooks()` HOC or `useDataHooks()` React Hooks
npm install @wix/data-hooks-react

# If you need UniDriver finders
npm install @wix/data-hooks-unidriver --save-dev

What is inside

@wix/data-hooks

  • dataHooks() — creates data-hooks generator. Examples
  • byDataHook() — builds CSS selector to find elements by data-hook html attribute. Examples

@wix/data-hooks-react

  • withDataHooks() – React HOC to wrap your component to pass dataHooks with base element generator as a prop. Examples
  • useDataHooks() – React hook to get dataHooks generator. Examples

@wix/data-hooks-unidriver

  • createFinders() – creates find() and findAll() methods to find UniDriver elements by data-hook attribute.

Basic Usage (without HOC or React Hooks)

🤓 See the example source code here

😎 Checkout advanced example to see dataHooks(), withDataHooks() and createFinders() usages

// Article.dataHooks.ts
import { dataHooks } from "@wix/data-hooks";

const articleDataHooks = dataHooks<{
  title;
  description;
  author: { id: string }
}>('article');

// dataHooks creates a JavaScript Proxy,
// so you do not need to pass the keys, types are enought
// Article.tsx
import { articleDataHooks } from "./Article.dataHooks.ts";

const Article: React.FC = ({dataHook, title, description, authorsList}) => (
  <article data-hook={dataHook}>
    <h1 data-hook={articleDataHooks.title()}>{title}</h1> {/* data-hook="article__title */}
    <p data-hook={articleDataHooks.description()}>{description}</p> {/* data-hook="article__description */}
    <ul>
      {authorsList.map(author => (
        <li
          key={author.id}
          data-hook={articleDataHooks.author({id: author.id})}
          {/* data-hook="article__author author--id_${author.id} */}
        >
          {author.name}
        </li>
      ))}
    </ul>
  </article>
)
// Article.spec.ts
import { byDataHook } from "@wix/data-hooks";
import { render } from '@testing-library/react';
import { Article } from './Article.tsx';
import { articleDataHooks } from "./Article.dataHooks.ts";

describe('<Article/>', () => {
  it('should render all authors', () => {
    const result = render(
      <Article
        title={"How to use data-hooks"}
        description={"A simple generator to share your data-hooks"}
        authorsList={[
          {name: 'John Simber', id: 'f19a3'},
          {name: 'Nick Figurt', id: '4ea2c'},
        ]}
      />
    )
    const selector = byDataHook(articleDataHooks.author()); // `[data-hook~="article__author"]`
    expect(result.baseElement.querySelectorAll(selector)).toHaveLength(2);
  })
})