ツー

日常の記録

ReactでSPAを手っ取り早く作る

久しぶりにclient appを作ろうとしたら 「create-react-app はもう推奨されとらんで」と言われてマジか??となったので、似たようなことのやり方をメモっておく。

vite がミニマムかつ create-react-app みたいなことができるらしいので使うのと、routerとして薄めな wouterCSStailwind を使っていく。

boilerplateの用意

npm create vite hoge --template react-ts

React TypeScript+SWC を選択

cd hoge
git init
git add * .eslintrc.cjs .gitignore
git commit -a -m "initial commit" 
npm install
npm install wouter
npm run dev

サーバが動くことを確認。

tailwindを入れる

command

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

tailwind.config.js

module.exports = {
  content: [
    "./index.html",
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

src/index.css

@tailwind base;
@tailwind components;
@tailwind utilities;

App.tsx

// import { useState } from 'react'
import { Router, Route, Link } from 'wouter';
import { useHashLocation } from 'wouter/use-hash-location';
import './App.css'

function App() {
  return (
    <>
      <Router hook={useHashLocation}>
        <h1 className="text-3xl font-bold underline mb-6">
          Hello world!
        </h1>
        <Link href='/test' className="bg-blue-600 hover:bg-blue-500 text-white rounded px-4 py-2">LINK</Link>
        <Route path="/test" component={Test} />
      </Router>
    </>
  )
}

function Test() {
  return <div>
    <h1 className="text-3xl font-bold underline mb-6">
      TestPage
    </h1>
    <Link href="/" className="bg-green-600 hover:bg-green-500 text-white rounded px-4 py-2">Return</Link>
  </div>
}

export default App

作る

あとはtailwindのコンポーネント一覧を見ながら作っていく。

Tailwind CSS Components - Tailwind UI

一般公開しないやつなのでhash routingで作る。

hash routingの場合web上にあるサンプルだとhooksを自ら定義するサンプルが多く見つかるが、下記の二行を書くだけで使えるようなったっぽい。

  • import { useHashLocation } from 'wouter/use-hash-location';
  • <Router hook={useHashLocation}>

参照