DEV Community

Cover image for React dot notation component with TS
Alex Suarez
Alex Suarez

Posted on

React dot notation component with TS

Yes I know, dot notation components are not very much used (libraries aside) in your projects, I've found out that is hard to check some legacy or green-field code containing some dot notation approach in it. Nevertheless is not an out-of-date pattern and overall is very useful. Let's jump in

When to do-notate components

There is not a most here, but from my personal point of view the right use of it is for components that "compose" themself all the time using necessary parts (other components)

The classic example would be a Table, think about it, your table will have thead, tbody, th, tr, and td, but you want to separate those parts into its own components, to add styles, or maybe to handle some logic and made it easy to test, but your table will always use it.

Import less and do more

For such components avoiding using dot notation causes imports to be long lines even if you use naming and try to do it from a single file
it would be cool if you simple import Table instead of Table plus all the small parts

import {Table, Thead, Tbody, Col, Row} from './table'
Enter fullscreen mode Exit fullscreen mode


import {Table} from './table'
Enter fullscreen mode Exit fullscreen mode

Typescript autocomplete

By using typescript (do it if you don't), also it's easy to autocomplete your Table component, since by typing now by typing "Table." will suggest you all the possible notations added to Table

Let's do it quickly

import React from "react";
import "./styles.css";

type TableCmp = React.FunctionComponent & {
  Thead: React.FC;
  Tbody: React.FC;
  Row: React.FC;
  Col: React.FC;

const Table: TableCmp = ({ children }): JSX.Element => <>{children}</>;
const Thead: React.FC = ({ children }): JSX.Element => (
const Tbody: React.FC = ({ children }): JSX.Element => (
const Row: React.FC = ({ children }): JSX.Element => <tr>{children}</tr>;
const Col: React.FC = ({ children }): JSX.Element => <td>{children}</td>;

Table.Thead = Thead;
Table.Tbody = Tbody;
Table.Row = Row;
Table.Col = Col;
Enter fullscreen mode Exit fullscreen mode

You can extrapolate this to any composition you need and extend the types for any components easily. Happy coding!

Discussion (2)

imcodingideas profile image
Joseph Chambers • Edited on

Though I like this "taste" as well, considering when the way that async boundaries work with webpack it's not recommended.

If you wanted to learn more about async boundaries:

alexandprivate profile image
Alex Suarez Author

Thanks you, huge fan of Jack Herrington BTW :)