npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@skbkontur/react-props2attrs

v0.1.3

Published

Translate react-props to attributes associated html-element

Downloads

1,067

Readme

react-props2attrs

Транслирует пропы реакт-компонентов в атрибуты ассоциированных html-элементов.

Ассоциированный элемент, в который транслируются пропы - это первый HTMLElement, найденный внутри компонента. Пакет работает только с 3-мя (из ~24) типами WorkTag: ClassComponent, FunctionComponent и HostComponent(div, span, table etc.). Остальные типы игнорируются.

Установка

Установка с npm:

npm i @skbkontur/react-props2attrs

Установка с yarn:

yarn add @skbkontur/react-props2attrs

Подключение

Основан на пакете @skbkontur/react-sorge. Поэтому подключение должно происходить до первого подключения пакета react-dom в приложении:

// entry.js

import '@skbkontur/react-props2attrs';
import ReactDOM from 'react-dom';
...

Фильтр

Для управление пропами, которые необходимо транслировать, используйте хелпер setFilter(filter: FilterType).

type FilterType = (fiber: Fiber) => string[] | null;

Установленный фильтр должен возвращать либо массив имён пропов, либо null, для игнорирования фильтра.
Имя компонента игнорирует фильтр.

import { setFilter } from '@skbkontur/react-props2attrs';

setFilter((fiber) => {
  // Пропускаем только контролы из пакета @skbkontur/react-ui
  if (typeof fiber.type?.__KONTUR_REACT_UI__ === 'string') {
    return null;
  }
  return [];
});

Примеры трансляции разных типов

Для наглядности представим, что в приложении есть такие компоненты:

const Foo = () => <span>Foo</span>;
const Bar = () => <Foo hello="world" />;

<Bar data-tid="Bar" />;

Тогда их ассоциированные html-элементы будут выглядеть так:

<span data-comp-name="Bar Foo" data-prop-hello="world" data-testid="Bar" data-tid="Bar">
  Foo
</span>

Обратите внимание на проп data-tid. Он транслирован в атрибут без приставки prop-. Также его значение продублировано в атрибут data-testid. Это дефолтное название атрибута для метода getByTestId() в библиотеке Testing Library.

Примеры трансляции всех специальных пропов:

| prop name | prop value | | attr value | attr name | | ---------------- | --------------------------------- | --- | -------------------------------- | ---------------------------- | | children | ~~не поддерживается~~ | ➜ | ~~не поддерживается~~ | | | style | { paddingLeft: 20, color: 'red' } | ➜ | {"paddingLeft":20,"color":"red"} | data-prop-style | | class | colored | ➜ | colored | data-prop-classname | | key | value | ➜ | value | data-key | | data-tid | MyControl | ➜ | MyControl | data-tid and data-testid | | *Имя компонента | ButtonCover | ➜ | *ButtonCover Button | data-comp-name |

* — Особенным образом транслируется имя компонента в атрибут data-comp-name.В этом атрибуте собираются имена всех react компонентов, с которыми был ассоциирован элемент. Имя компонента транслируется всегда, независимо от настроек фильтра.

Примеры трансляции обычных пропов:

| prop name (type) | prop value | | attr value | attr name | | ---------------- | ---------- | --- | ---------- | ------------------------ | | string | str | ➜ | str | data-prop-string | | number | 123 | ➜ | 123 | data-prop-number | | array | ['a', 'b'] | ➜ | ["a","b"] | data-prop-array | | object | { a: 'b' } | ➜ | {"a":"b"} | data-prop-object | | func | () => {} | ➜ | true | data-prop-func | | boolean | false | ➜ | false | data-prop-boolean | | empty_string | | ➜ | undefined | data-prop-empty_string | | null | null | ➜ | undefined | data-prop-null | | undefined | undefined | ➜ | undefined | data-prop-undefined |