Code Style
- 1 React Style:
- 1.1 Files and Naming:
- 1.2 Indentation:
- 1.3 JSX:
- 1.4 React Components:
- 1.5 Quotes:
React Style:
Based on Airbnb's official React style guide: javascript/react at master · airbnb/javascript.
This section takes a small but important subset of that style guide for Structs.sh.
Files and Naming:
One component per file
Prefer functional components over class components
They're easier to test
Less code, hence easier to read and maintain
Possible performance boost in future versions of React
Only use class components when there's complex internal state
Use
.jsx
extension for React components and.js
for every other fileIf using TypeScript, then use
.tsx
and.ts
Naming
PascalCase
for React componentsGive it the same name as the filename. Eg. for
LinkedList.jsx
, name the React component inside to beLinkedList
camelCase
for everything else
Indentation:
Splitting up long prop lines:
<Foo superLongParam="bar" anotherSuperLongParam="baz" />
Conditional rendering:
// && operator { showButton && <Button />; } // Ternary operator () { someConditional ? <Foo /> : <Foo superLongParam="bar" anotherSuperLongParam="baz" />; }
JSX:
Spacing
// Very bad <Foo bar={ baz } /> // Good <Foo bar={baz} />
Wrap JSX in parentheses
return <MyComponent variant="long body" foo="bar" />;
React Components:
Use 'object destructuring' to get prop arguments
// Don't repeat props everywhere :( const Input = (props) => { return <input value={props.value} onChange={props.onChange} />; }; // Destructure and use the straight values :) const Input = ({ value, onChange }) => <input value={value} onChange={onChange} />;
Always set default props so that the component never crashes when you don't pass in a specific prop
const Component = ({ title: 'Default Title', subtitle: 'Generic Subtitle' }) => { return ( <div> ... </div> ); }
Quotes:
Use double quotes
"..."
for prop passing and'...'
for everything else