> For the complete documentation index, see [llms.txt](https://tech.x2bee.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tech.x2bee.com/dev-guide/pjt-prepare/publish-your-docs/store-front-framewok-next.js/02./1..md).

# 1. 코딩 스타일 가이드

이 문서는 Nextjs 프로젝트 개발 시 코딩 스타일 작성 방법을 설명합니다.

{% stepper %}
{% step %}

### Componentization

{% hint style="info" %}
가장 중요함: 코딩 후에 refactor도 필요하지만, 우선 처음부터 component화 시키는 것이 중요합니다.
{% endhint %}

가독성과 코드 재사용을 위해서 반드시 component화가 필요합니다. Composable commerce의 필수 요건이라 할 수 있습니다.

예시: layout.tsx

{% code title="layout.tsx" %}

```
```

{% endcode %}

```tsx
const Layout = ({ children }) => (
  <div className="layout">
    <header> Header content ... ... </header>
    <main>{children}</main>
    <footer> Footer content ... ... </footer>
  </div>
);
export default Layout;
```

이 파일 하나에 수 천 line 코딩하지 말고, Header와 Footer를 src/components/에 코딩 후 import 합니다.

{% code title="layout.tsx (refactored)" %}

```tsx
import Header from '@/components/header';
import Footer from '@/components/footer';

const Layout = ({ children }) => (
  <div className="layout">
    <Header />
    <main>{children}</main>
    <Footer />
  </div>
);
export default Layout;
```

{% endcode %}
{% endstep %}

{% step %}

### Nullish Coalescing

물음표 두 개 ??를 사용하는 문법입니다. ES2020에 도입된 JavaScript 문법이며, REST API의 response를 json으로 받아 체크할 때 유용합니다.

예시 설명:

* false || true; // => true
* false ?? true; // => false

false라는 값은 boolean 이고, 기본값 연산자 ??는 **undefined 혹은 null** 일 때만 뒤의 default 값을 사용합니다. 즉 응답 json에서 의도적인 빈 문자열 "" 값을 받을 때 이를 변형하지 않습니다.

사용 예시:

{% code title="예시" %}

```javascript
const name = foo ?? "default value";
```

{% endcode %}
{% endstep %}

{% step %}

### 고차함수

.map, .filter, .reduce의 문법을 익히면 좋습니다.

예시:

{% code title="React (map) 예시" %}

```jsx
return (
  <ul>
    {items.map((item, index) => (
      <li key={index}>
        {item}
      </li>
    ))}
  </ul>
)
```

{% endcode %}
{% endstep %}

{% step %}

### key

Next.js 고유가 아닌 모든 React 기반으로 코딩할 때 .map()을 쓰면 항상 key 값을 주어야 합니다. 처음 React를 접할 때 가장 많이 하는 실수입니다. 위의 고차함수(map) 예시를 참고하세요.
{% endstep %}

{% step %}

### try-catch

예시:

{% code title="fetch 예시" %}

```javascript
async function fetchData() {
  // An async function for fetching data from an API
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error(`API call failed with status: ${response.status}`);
    }
    return await response.json();
  } catch (error) {
    // Error handling or logging logic
    throw error;
  }
}
```

{% endcode %}
{% endstep %}

{% step %}

### ternary operator

예시:

{% code title="ternary 예시" %}

```jsx
return (
  <>
    {isLogin ? <div>Logged in</div> : <div>Not Logged in</div>}
  </>
)
```

{% endcode %}
{% endstep %}

{% step %}

### Destructuring

예시: without destructuring

{% code title="without destructuring" %}

```javascript
function displayPerson(person) {
  const name = person.name;
  console.log(name);
}
```

{% endcode %}

예시: with destructuring

{% code title="with destructuring" %}

```javascript
function displayPerson({ name, age, job }) {
  console.log(name);
}
```

{% endcode %}
{% endstep %}

{% step %}

### optional chaining

값이 없을 때 나는 오류를 방지하기 위해 required field가 아니면 물음표 입력:

예시:

```javascript
productList?.info?.color
```

{% endstep %}
{% endstepper %}
