0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nextjsでコンポーネント(部分テンプレート)作成

Posted at

今回はコンポーネントの作成について書いていきます
例えばですが各ページでヘッダーを使いまわしたい
部分的に同じだから再度のせるのが手間だと思いませんか
コンポーネントはそれを解決します

1,コンポーネントフォルダの作成

今回は仮にヘッダーを作成するとします。
srcより後のフォルダ名(components),ファイル名(Header)は
基本変えても大丈夫ですので、ただ他の人が見てもわかりやすい
ように命名しときましょう。

src/components/Header.tsx

仮にこのような内容で記述します

// src/components/Header.tsx
import React from 'react';
import Link from 'next/link';

const Header: React.FC = () => {
  return (
    <header>
      <nav>
        <ul>
          <li>
            <Link href="/"><a>Home</a></Link>
          </li>
          <li>
            <Link href="/about"><a>About</a></Link>
          </li>
          {/* 他のナビゲーションリンクを追加 */}
        </ul>
      </nav>
    </header>
  );
};

export default Header;

2,ページにheaderコンポーネントを追加します

あとは入れたい場所に<Headerと書けば候補がでてきますので
内容から作成したcomponentsを指定してenterすればimport部分も追加されて
埋め込まれます

// src/pages/index.tsx (トップページ)
import React from 'react';
import Header from '../components/Header';

const HomePage: React.FC = () => {
  return (
    <div>
      <Header />
      <h1>Welcome to the Home Page</h1>
      <p>This is the main page of the website.</p>
    </div>
  );
};

export default HomePage;

3,まとめ

これの応用でサイドバー,フッターも追加できますので
今後のアプリ作成で役立ててください

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?