1
1

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の超基礎

Posted at

はじめに

1年前にやったreactを忘れてしまったので、基礎から思い出しをしました。
ハンズオン形式でと思ったのですが、思った以上に基礎的なものになってしまいました。
かなり勉強初期段階の方向けの資料になっております。

手順

Step1 導入

プロジェクトをViteで作成

npm create vite@latest my-lp-project -- --template react-ts
  • プロジェクト名:my-lp-project(好きな名前でOK)
  • フレームワーク:React
  • バリアント:TypeScript

vitteとはは下記サイトを参考にさせていただきました。
https://qiita.com/tomada/items/91c489e41a20a2fd11ea

プロジェクトディレクトリに移動して起動

cd my-lp-project
npm install
npm run dev

Emotionのインストール(CSS-in-JS)

npm install @emotion/react @emotion/styled

Step2 Reactの基本文法

HTMLを書く

function App() {
  return (
    <div>
      <h1>Hello, React!</h1>
      <p>これはJSXで書かれたHTMLです。</p>
    </div>
  );
}

export default App;

【ポイント】

  • HTMLのように見えるけど、JavaScriptの中で書くHTML風構文。
  • タグは1つの親要素で囲む必要がある。

Props

src/components/Greeting.tsxを作成。
下記を打ち込む。

type GreetingProps = {
	name: string;
};

const Greeting = ({ name }: GreetingProps) => {
	return <p>こんにちは、{name}さん!</p>;
};

export default Greeting;

App.tsx

import "./App.css";
import Greeting from "./components/Greeting";

function App() {
	return (
		<div>
			<h1>Hello, React!</h1>
			<Greeting name="太郎" />
		</div>
	);
}

export default App;

【ポイント】

  • name="太郎"のように、親から子へデータを渡すのが props。
  • Greetingコンポーネントはnameという値を受け取って使えるようにする。

State

import { useState } from 'react';

function App() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h1>Hello, React!</h1>
      <button onClick={() => setCount(count + 1)}>
        カウント: {count}
      </button>
    </div>
  );
}

【ポイント】

  • useState(0)で状態を作成(今回は数値)。
  • setCountを呼ぶと、画面が自動で再描画される。
  • イベント(onClickなど)に関数を渡して動きをつけることができる。

Step3 emotion(CSS)

import "./App.css";
import styled from "@emotion/styled";

function App() {
	return <Box>これはスタイル付きのBoxです</Box>;
}

const Box = styled.div`
	padding: 16px;
	background-color: #f0f0f0;
	border-radius: 8px;
`;
export default App;

【ポイント】

  • コンポーネント単位でCSSを適用できる。
  • 同じデザインを複数箇所で使う時に便利である。
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?