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
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
dataHooks()
— creates data-hooks generator. ExamplesbyDataHook()
— builds CSS selector to find elements bydata-hook
html attribute. Examples
withDataHooks()
– React HOC to wrap your component to passdataHooks
withbase
element generator as a prop. ExamplesuseDataHooks()
– React hook to getdataHooks
generator. Examples
createFinders()
– createsfind()
andfindAll()
methods to find UniDriver elements bydata-hook
attribute.
🤓 See the example source code here
😎 Checkout advanced example to see
dataHooks()
,withDataHooks()
andcreateFinders()
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);
})
})