Обложка канала

Paqmind - про Frontend / Web / React

444 @Paqmind

Канал о программировании и веб-разработке. Мы создаем уникальные туториалы, гайды, составляем дорожные карты для самообучения. Основные темы: Frontend, React, Next.js.

  • Paqmind - про Frontend / Web / React

    For quite a while I had ESLint rule `@typescript-eslint/no-unused-vars` disabled cause (I thought) it duplicates TypeScript rules noUnusedLocals and noUnusedParams. Few experiments confirmed that belief. Today I reenabled that ESLint rule on quite a big codebase and, to my surprise ... discovered that `noUnusedLocals` does miss some unused vars! I didn't notice a *pattern of missing* yet (TS bugs?) but the point is that EsLint may find "unused-var" bugs that TS doesn't. Both TS rules are disabled in Deno b.t.w and they recommend to use Linter instead. So I decided to follow the same path and recommend it to you. - Disable `noUnusedLocals` and `noUnusedParams` to have more flexibility while development (it really helps). - Enable `@typescript-eslint/no-unused-vars` to catch "unused-something" places The latter will need an extra config like: ``` "@typescript-eslint/no-unused-params": ["error", {"argsIgnorePattern": "^_", "varsIgnorePattern": "^_"} ], ```
  • Paqmind - про Frontend / Web / React

    How to use `React.forwardRef` & `React.memo` in TypeScript with Namespace pattern For example you have the following working code:
    export function Flex(props : FlexProps) : JSX.Element { ... }
    
    function FlexRow(props : FlexRowProps) : JSX.Element { ... }
    
    Flex.Row = FlexRow // !!! works 
    
    But it immediately breaks if you add memo or forwardRef:
    export const Flex = React.forwardRef(function Flex(props : FlexProps, ref : any)) : JSX.Element { ... })
    
    function FlexRow(props : FlexRowProps) : JSX.Element {}
    
    Flex.Row = FlexRow // !!! Error: property `Row` does not exist on ...
    
    React developers have been struggling with this problem for years. And the proposed solutions are insanely verbose:
    export interface Props = {
       ...yourPropsHere;
    };
    
    export interface CompoundedComponent extends React.ForwardRefExoticComponent<Props & React.RefAttributes<HTMLInputElement>> {
       yourStaticFunctionOrSomethingLikeThat: () => void;
    }
    
    const Component = React.forwardRef<HTMLInputElement, Props>((props, ref) => (
        <input ref={ref} {...props} />
    )) as CompoundedComponent;
    
    Component.yourStaticFunctionOrSomethingLikeThat = () => {};
    
    Total mess:
    type WithStatics<
      C extends React.ComponentType<any>,
      StaticCmps extends {
        [attachedComponents: string]: React.ComponentType<any>;
      } = {}
    > = C & StaticCmps;
    
    type GridProps = {};
    type CellProps = {};
    
    const Cell: React.FunctionComponent<CellProps> = props => <div {...props} />;
    
    const Grid: WithStatics<
      React.FunctionComponent<GridProps>,
      { Cell: typeof Cell }
    > = props => <div {...props} />;
    
    Grid.defaultProps = { color: "red" };
    Grid.Cell = Cell;
    
    Recently, I have found a much easier way to achieve the same result:
    tsx
    const Flex = React.forwardRef(function Flex(...) {
      ...
    })
    
    const FlexRow = React.forwardRef(...)
    const FlexColumn = React.forwardRef(...)
    
    const FlexNamespace = Object.assign(Flex, {Row: FlexRow, Column: FlexColumn})
    
    export {FlexNamespace as Flex}
    
    Now you can use Flex, Flex.Row, and Flex.Column with TS being happy. The magic line is Object.assign which does not cause the same type issue as Flex.Row = FlexRow does.
  • Paqmind - про Frontend / Web / React

    ^ responsive макеты в React и увязка с дизайном на 12-колончатой сетке. Кому интересны подробности – пишите в комментариях.
  • Реклама

  • Paqmind - про Frontend / Web / React

    Флексы, Гриды и 12-колончатый макет.
  • Paqmind - про Frontend / Web / React

    По вопросу выше правильный ответ: "можно, начиная, с ES2015". Вижу, что для большинства это новость, значит на канал подписаны не зря 😉
  • Paqmind - про Frontend / Web / React

    Мнения разделились, как обычно 🙂 Уточнение к ответу дано в комментариях (иконка справа).
  • Paqmind - про Frontend / Web / React

    Вопрос: можно ли полагаться на порядок нечисловых ключей в простом объекте JS при итерации? Или, иными словами, можно ли представлять упорядоченные коллекции словарём вида {first: 1, second: 2}?
  • Paqmind - про Frontend / Web / React

    Спасибо всем кто проголосовал. По результатам отпишусь позже.