Frontend Handbook

This guide covers how we write frontend code at Sentry, and is specifically focussed on 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.

Directory structure

The frontend codebase is currently located under static/app in sentry and static/getsentry in getsentry.

Folder & File structure

File Naming

  • 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 like dataScrubbing/editModal.

Using index.(j|t)sx?$

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.(j|t)sx?$ 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.

React

Defining React components

New components should be created as functional components, using function declarations instead of arrow functions. Props should be declared above the component.

Copied
type Props = {
  author: object;
  content: string;
  onEdit: (value: string) => void;
};

function Note(props: Props) {
  // use destructuring assignment for props
  const {author, content, onEdit} = props;
  
  handleChange = value => {
    const user = ConfigStore.get('user');

    if (user.isSuperuser) {
      onEdit(value);
    }
  };

  return (
    <div onChange={handleChange}>{content}</div>
  );
}

export default Note;

Components vs views

Both the app/components/ and app/views folders contain React components.

  • Use a view for UI that will typically not be reused in other parts of the codebase
  • Use a component for UI that is designed to be highly reusable.

PropTypes

Use them, be explicit, use the shared custom proptypes when possible.

Prefer Proptypes.arrayOf to PropTypes.array and PropTypes.shape to PropTypes.object

If you’re passing Objects with an important, well defined set of keys (that your component relies on) then define them explicitly with PropTypes.shape:

Copied
PropTypes.shape({
  username: PropTypes.string.isRequired,
  email: PropTypes.string
})

If you’re re-using a custom prop-type or passing around a common shared shape like an organization, project, or user, then be sure to import a proptype from our useful collection of custom ones! https://github.com/getsentry/sentry/blob/master/static/app/sentryTypes.tsx

Event handlers

We use different prefixes to better distinguish event handlers from event callback props.

Use the handle prefix for event handlers, e.g:

Copied
<Button onClick={this.handleDelete}/>

For event callback props passed to the component use the on prefix, e.g:

Copied
<Button onClick={this.props.onDelete}>

CSS and Emotion

  • Use Emotion, use the theme object.
  • The best styles are ones you don’t write - whenever possible use existing components.
  • New code should use the css-in-js library e m o t i o n - it lets you bind styles to elements without the indirection of global selectors. You don’t even need to open another file!
  • Take constants (z-indexes, paddings, colors) from props.theme
Copied
import styled from 'react-emotion';

const SomeComponent = styled('div')`
  border-radius: 1.45em;
  font-weight: bold;
  z-index: ${p => p.theme.zIndex.modal};
  padding: ${p => p.theme.grid}px ${p => p.theme.grid * 2}px;
  border: 1px solid ${p => p.theme.borderLight};
  color: ${p => p.theme.purple};
  box-shadow: ${p => p.theme.dropShadowHeavy};
`;

export default SomeComponent;

stylelint Errors

"No duplicate selectors"

This happens when you use a styled component as a selector, we need to tell stylelint that what we are interpolating is a selector by using comments to assist the linter. e.g.

Copied

const ButtonBar = styled("div")`
  ${/* sc-selector */Button) {
     border-radius: 0;
  }
`;

See https://styled-components.com/docs/tooling#interpolation-tagging for other tags and more information.

State management

We currently use Reflux for managing global state.

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.

We are currently exploring alternatives to the Reflux library for future use.

Testing

Note: Your filename needs to be .spec.jsx or .spec.tsx for jest to run run it!

We have useful fixtures defined in setup.ts Use these! If you are defining mock data in a repetitive way, it’s probably worth adding this this file. 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:

Copied
wrapper.find('ExpandButton').simulate('click');
await tick();
expect(wrapper.find('CommitRow')).toHaveLength(2);

Selectors

If you are writing jest tests, you can use a Component (and Styled Component) names as a selector. Additionally, if you need to use a DOM query selector, use data-test-id instead of a class name. We currently don’t, but it is something we can use babel to strip out during the build process.

Undefined theme properties in tests

Instead of using mount() from enzyme ...use this: import {mountWithTheme} from 'sentry-test/enzyme' so that the component under test gets wrapped with a <ThemeProvider>.

Babel Syntax Plugins

We have decided to only use ECMAScript proposals that are in stage 3 (or later) (See TC39 Proposals). Additionally, because we are migrating to typescript, we will align with what their compiler supports. The only exception to this are decorators.

New Syntax

Optional Chaining

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.

Syntax

The Optional Chaining operator is spelled ?.. It may appear in three positions:

Copied
obj?.prop       // optional static property access
obj?.[expr]     // optional dynamic property access
func?.(...args) // optional function or method call

From https://github.com/tc39/proposal-optional-chaining

Nullish Coalescing

This is a way to set a "default" value. e.g. previously you would do something like

Copied
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

Copied
let x = volume ?? 0.5

It will only default to 0.5 if volume is null or undefined.

Syntax

Base case. If the expression at the left-hand side of the ?? operator evaluates to undefined or null, its right-hand side is returned.

Copied
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

From https://github.com/tc39/proposal-nullish-coalescing

Lodash

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.

Typescript

You can edit this page on GitHub.