React & Typescript Coding Standards
This style guide is enforced via ESLint and Prettier, and integrated into our CI process.
Naming
- Extensions: Use
.tsxextension for React components. - Filenames: Use kebab-case for filenames e.g.
my-component.tsx. - Reference Naming: Use PascalCase for React components and camelCase for their instances. eslint:
react/jsx-pascal-case
// bad
import reservationCard from "./ReservationCard";
// good
import ReservationCard from "./ReservationCard";
// bad
const ReservationItem = <ReservationCard />;
// good
const reservationItem = <ReservationCard />;
- Component Naming: Use the component name for the filename. For example
MyComponentshould have the filenamemy-component.tsx.
// bad
import Footer from "./FooterComponent";
// bad
import Footer from "./Footer/index";
// good
import Footer from "./Footer";
- Order of Words: Component names should start with the highest-level (most general) words and end with descriptive modifying words.
// bad
components/
|- ClearSearchButton.tsx
|- ExcludeFromSearchInput.tsx
|- LaunchOnStartupCheckbox.tsx
|- RunSearchButton.tsx
|- SearchInput.tsx
|- TermsCheckbox.tsx
// good
components/
|- SearchButtonClear.tsx
|- SearchButtonRun.tsx
|- SearchInputQuery.tsx
|- SearchInputExcludeGlob.tsx
|- SettingsCheckboxTerms.tsx
|- SettingsCheckboxLaunchOnStartup.tsx
- Props Naming: Avoid using DOM component prop names for different purposes.
// bad
<MyComponent style="fancy" />
// bad
<MyComponent className="fancy" />
// good
<MyComponent variant="fancy" />
Props
- Always use camelCase for prop names.
// bad
<Foo
UserName="hello"
phone_number={12345678}
/>
// good
<Foo
userName="hello"
phoneNumber={12345678}
/>
- Avoid using an array index as
keyprop, prefer a unique ID. Why?.
// bad
{
todos.map((todo, index) => <Todo {...todo} key={index} />);
}
// good
{
todos.map((todo) => <Todo {...todo} key={todo.id} />);
}
- Omit the value of the prop when it is explicitly
true.
// bad
<Foo hidden={true} />
// good
<Foo hidden />
- Always include a helpful, non-redundant
altprop on<img>tags. If the image is presentational,altcan be an empty string or the<img>must haverole="presentation". eslint:jsx-a11y/alt-text
// bad
<img src="hello.jpg" />
// bad
<img src="hello.jpg" alt="Picture of me waving hello" />
// good
<img src="hello.jpg" alt="Me waving hello" />
// good
<img src="hello.jpg" alt="" />
// good
<img src="hello.jpg" role="presentation" />
Tags
- Always self-close tags that have no children. eslint:
react/self-closing-comp
// bad
<Foo variant="stuff"></Foo>
// good
<Foo variant="stuff" />
- If your component has multi-line properties, close its tag on a new line. eslint:
react/jsx-closing-bracket-location
// bad
<Foo
bar="bar"
baz="baz" />
// good
<Foo
bar="bar"
baz="baz"
/>