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?

ReactでUIを作る方法

Last updated at Posted at 2024-10-20

今回はReactで簡単なUIを作る方法について記事にしたいと思います。
初学者のかたはわからない用語なども出てくると思いますので、公式ドキュメントについても記事にしています。

1. React プロジェクトの準備

React プロジェクトを始めるためには、以下のコマンドで create-react-app を使ってプロジェクトを作成します。

プロジェクトの作成(個人的にはVScodeがおすすめです)

npx create-react-app my-app --template typescript
cd my-app
npm start

ブラウザで http://localhost:3000 にアクセスすると、React の初期画面が表示されます。

2. React コンポーネントの作成

React では、UI はコンポーネントを組み合わせて作成します。以下は、Button コンポーネントと App コンポーネントの例です。

Button コンポーネントの作成
src/Button.tsx

import React from 'react';

interface ButtonProps {
  label: string;
  onClick: () => void;
}

const Button: React.FC<ButtonProps> = ({ label, onClick }) => {
  return (
    <button onClick={onClick} style={{ padding: '10px', margin: '5px' }}>
      {label}
    </button>
  );
};

export default Button;

3. カウンターアプリの作成

次に、ボタンを使ったカウンターアプリを構築します。

App コンポーネントの作成
src/App.tsx

import React, { useState } from 'react';
import Button from './Button';

const App: React.FC = () => {
  const [count, setCount] = useState(0);

  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);

  return (
    <div style={{ textAlign: 'center', marginTop: '50px' }}>
      <h1>カウンター: {count}</h1>
      <Button label="+1" onClick={increment} />
      <Button label="-1" onClick={decrement} />
    </div>
  );
};

export default App;

useState フックを使って、カウンターの状態を管理します。
クリックイベントで count を増減させます。

4. スタイリングの追加

CSS を使って UI をさらに改善することができます。以下は、CSS を使ってスタイルを整える例です。

src/index.css

body {
  margin: 0;
  padding: 0;
  font-family: 'Arial', sans-serif;
  background-color: #f0f0f0;
}

button {
  font-size: 18px;
  cursor: pointer;
}

h1 {
  color: #333;
}

ボタンと背景の色を変更し、テキストの色とフォントも調整しています。

5. UI の確認

プロジェクトのルートで以下のコマンドを実行します。

npm start

ブラウザで http://localhost:3000 にアクセスすると、以下のようなカウンターアプリが表示されます。

6. UI を改善するためのポイント

レスポンシブデザイン: CSS のメディアクエリを使って、画面サイズに応じたレイアウトに対応します。
UI ライブラリの活用: Material-UI や Ant Design のような UI ライブラリを使用することで、簡単にスタイリッシュな UI を構築できます。

7. さらに発展させる

以下のような機能を追加することで、より魅力的な UI を作成できます。

入力フォームを追加して、ユーザーからのデータを受け取る。
React Router を使ってページ遷移を実装する。

React Routerについては別途記事にしていますので、こちらを見ていただけると嬉しいです。

Redux を使ったグローバルな状態管理を導入する。

Reduxについては別途記事にしていますので、こちらを見ていただけると嬉しいです。

毎日更新していますので、@y-t0910をフォローしていただけると嬉しいです。

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?