Frontend
How we write frontend code at Sentry.
This guide specifically focuses on the frontend part of the Sentry and Getsentry codebases. It assumes you are using the eslint rules outlined by eslint-config-sentry; hence code style enforced by these linting rules will not be discussed here.
The frontend codebase is currently located under static/app
in sentry and static/getsentry
in getsentry.
- Name a file meaningfully, based on how the module's functions, or classes are used or the application section they are used in.
- Unless necessary, don't use prefixes or suffixes (ie.
dataScrubbingEditModal
,dataScrubbingAddModal
) instead favor names likedataScrubbing/editModal
. - Tip: Name the file to match the component or function that is being exported. This makes it easier for people to know what is inside the file, and re-use it.
Having an index
file in a folder provides a way to implicitly import the main file without specifying it.
The use of an index file should comply with the following rules:
- If the folder is created to group components that are used together, and there is an entrypoint component, that uses the components within the grouping (examples, avatar, idBadge). The entrypoint component should be the index file.
- Don't use an
index.tsx?$
file if the folder contains components used in other parts of the app regardless of the entrypoint file. (ie, actionCreators, panels) - Don't use an index file just to re-export. Prefer importing individual components instead.
New components should be created as functional components, using function declarations instead of arrow functions. Props should be declared above the component.
interface Props {
author: object;
content: string;
onEdit: (value: string) => void;
}
// use destructuring assignment for props
export default function Note({ author, content, onEdit }: Props) {
const handleChange = (value) => {
const user = ConfigStore.get("user");
if (user.isSuperuser) {
onEdit(value);
}
};
return <div onChange={handleChange}>{content}</div>;
}
Both the app/components/
and app/views/
folders contain React components.
- Put files in
app/views/
when the component can not be reused in other parts of the codebase.- Typically only layout/construction of full pages should be in this folder. ie: files that are imported by routes.tsx.
- Put files into
app/components/
for anything else that could be reused.- If the component accepts any prop beyond
RouteComponentProps
then it very likely belongs insideapp/components/
- If the component accepts any prop beyond
We do not follow any strict "prefer type over interface" rules for type declarations, so using either is at your discretion. That being said, there are functional differences between the two that you should be aware of so you can use them appropriately.
A simple guiding principle is to prefer interfaces when you require declaration merging. The reason for that is that type intersections are poor at detecting conflicts, produce unexpected or unwanted results and when used in combination with large types perform worse than interfaces.
Example:
// This is valid and the outcome is a "never" type
type A = { color: "blue" } & { color: "red" };
interface B {
color: "blue";
}
// Interface 'C' incorrectly extends interface 'B'.
// Types of property 'color' are incompatible.
interface C extends B {
color: "red";
}
We use different prefixes to better distinguish event handlers from event callback props.
Use the handle
prefix for event handlers, e.g:
<Button onClick={this.handleDelete} />;
For event callback props passed to the component use the on
prefix, e.g:
<Button onClick={this.props.onDelete}>
For React Hooks tips check out this page.
Prefer the built-in useState
and useReducer
react hooks for state whenever possible.
We currently also have Reflux and MobX included in package.json but their use for new cases is discouraged.
Reflux implements the unidirectional data flow pattern outlined by Flux. Stores are registered under app/stores
and are used to store various pieces of data used by the application. Actions need to be registered under app/actions
. We use action creator functions (under app/actionCreators
) to dispatch actions. Reflux stores listen to actions and update themselves accordingly.
For React Testing Library (RTL) tips check out this page.
Note: Your filename needs to be .spec.tsx
for jest to run run it!
We have useful fixtures defined in tests/js/fixtures/ Use these! If you are defining mock data in a repetitive way, it’s probably worth adding this these files. routerContext
is a particularly useful one for providing the context object that most view are written to rely on.
Client.addMockResponse()
is the best way to mock API requests. it’s our code so if it’s confusing you, just put console.log()
statements into its logic!
Marking your test method async
and using the await tick();
utility can let the event loop flush run events and fix this:
wrapper.find("ExpandButton").simulate("click");
await tick();
expect(wrapper.find("CommitRow")).toHaveLength(2);
We have decided to only use ECMAScript proposals that are in stage 3 (or later) (See TC39 Proposals). The only exception to this are decorators.
Optional chaining helps us access [nested] objects without having to check for existence before each property/method access. If we try to access a property of an undefined
or null
object, it will stop and return undefined
.
The Optional Chaining operator is spelled ?.
. It may appear in three positions:
obj?.prop // optional static property access
obj?.[expr] // optional dynamic property access
func?.(...args) // optional function or method call
This is a way to set a "default" value. e.g. previously you would do something like
let x = volume || 0.5;
Which is a problem since 0
is a valid value for volume
, but because it evaluates to false
-y, we do not short circuit the expression and the value of x
is 0.5
If instead we used nullish coalescing
let x = volume ?? 0.5;
It will only default to 0.5
if volume
is null
or undefined
.
Base case. If the expression at the left-hand side of the ?? operator evaluates to undefined or null, its right-hand side is returned.
const response = {
settings: {
nullValue: null,
height: 400,
animationDuration: 0,
headerText: "",
showSplashScreen: false,
},
};
const undefinedValue =
response.settings.undefinedValue ?? "some other default"; // result: 'some other default'
const nullValue = response.settings.nullValue ?? "some other default"; // result: 'some other default'
const headerText = response.settings.headerText ?? "Hello, world!"; // result: ''
const animationDuration = response.settings.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings.showSplashScreen ?? true; // result: false
Be sure to not import lodash
utilities using the default lodash
package. There is an eslint
rule to make sure this does not happen. Instead, import the utility directly, e.g. import isEqual from 'lodash/isEqual';
.
Previously we used a combination of lodash-webpack-plugin and babel-plugin-lodash but it is easy to overlook these plugins and configuration when trying to use a new lodash utility (e.g. this PR). With webpack
tree shaking and eslint
enforcement, we should be able to maintain reasonable bundle sizes.
See this PR for more information.
We prefer using optional chaining and nullish coalescing over get
from loadash/get
.
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").