[React] Basic Rules

HYl·2022년 3월 3일
0

배열의 인덱스를 key 속성 값으로 사용하는 것을 피하고, 유니크한 ID 값을 사용하라.
=> Why? Not using a stable ID is an anti-pattern because it can negatively impact performance and cause issues with component state.

// bad
{todos.map((todo, index) =>
  <Todo
    {...todo}
    key={index}
  />
)}

// good
{todos.map(todo => (
  <Todo
    {...todo}
    key={todo.id}
  />
))}

Always define explicit defaultProps for all non-required props.
=> Why? propTypes are a form of documentation, and providing defaultProps means the reader of your code doesn’t have to assume as much. In addition, it can mean that your code can omit certain type checks.

// bad
function SFC({ foo, bar, children }) {
  return <div>{foo}{bar}{children}</div>;
}
SFC.propTypes = {
  foo: PropTypes.number.isRequired,
  bar: PropTypes.string,
  children: PropTypes.node,
};

// good
function SFC({ foo, bar, children }) {
  return <div>{foo}{bar}{children}</div>;
}
SFC.propTypes = {
  foo: PropTypes.number.isRequired,
  bar: PropTypes.string,
  children: PropTypes.node,
};
SFC.defaultProps = {
  bar: '',
  children: null,
};

항상 참조 콜백 함수를 사용하라.

// bad
<Foo
  ref="myRef"
/>

// good
<Foo
  ref={(ref) => { this.myRef = ref; }}
/>

리액트 컴포넌트의 내부 메소드를 위해 언더바 문자를 사용하면 안 된다.
=> Why? Underscore prefixes are sometimes used as a convention in other languages to denote privacy.

// bad
React.createClass({
  _onClickSubmit() {
    // do stuff
  },

  // other stuff
});

// good
class extends React.Component {
  onClickSubmit() {
    // do stuff
  }

  // other stuff

  • img 태그에는 항상 alt 속성을 작성한다. 만약 이미지가 표현 가능하다면, alt 값은 빈 문자열이 될 수 있거나 img는 반드시 role="presentation" 속성을 가지고 있어야 한다
  • img 태그의 alt 속성 값으로 "image", "photo", "picture" 와 같은 단어를 사용하면 안 된다.
    => 왜? 스크린리더는 이미 img 태그를 이미지로 인지하고 있기 때문에, alt 속성 값에 반복으로 해당 정보를 포함할 필요가 없다.
// bad
<img src="hello.jpg" />

// good
<img src="hello.jpg" alt="Me waving hello" />

// good
<img src="hello.jpg" alt="" />

// good
<img src="hello.jpg" role="presentation" />

profile
꾸준히 새로운 것을 알아가는 것을 좋아합니다.

0개의 댓글