Motomichi Works Blog

モトミチワークスブログです。その日学習したことについて書いている日記みたいなものです。

ローカルのreact-appをスマホ端末から閲覧できるようにする

参考にさせていただいたページ

概要

create-react-appで作成した開発中のローカル環境にスマホなどの別端末からアクセスできるようにします。

コマンド

それぞれ以下のコマンドで閲覧できるようになります。
ipアドレスは、ローカルホスト起動時にターミナルに表示されますし、Macの場合はシステム環境設定のネットワークからも確認できます。
192.168.xx.xx みたいなipだと思います。
ご自身の環境で確認してください。

npm

HOST=0.0.0.0 npm run start

yarn

HOST=0.0.0.0 yarn start

create-react-appしてbuildしたアプリケーションをnetlifyにデプロイしてリロードしたとき404になるのを解決する

参考にさせていただいたページ

解決したい事象

以下の手順を実行したときにnetlifyが用意している404ページが表示されてしまいました。

  1. yarn create react-app my-app --template typescript でreactアプリケーションをcreateします。
  2. /exampleページを作ります。
  3. react-router-domのLinkコンポーネントで、rootページから/exampleページへのリンクを設置します。
  4. yarn build します。
  5. buildされたディレクトリ/buildをnetlifyにデプロイします。
  6. https://xxxxx.netlify.app(rootページ)」にアクセスします。
  7. リンクをクリックして「 https://xxxxx.netlify.app/example」に遷移します。
  8. リロードするとnetlifyが用意している404ページが表示されてしまいます。

以下のようなページが表示されました。 f:id:motomichi_works:20211228191126p:plain

Page Not Found
Looks like you've followed a broken link or entered a URL that doesn't exist on this site.

Back to our site

If this is your site, and you weren't expecting a 404 for this path, please visit Netlify's "page not found" support guide for troubleshooting tips.

どうしたいか

rootページ以外でリロードしたとき、サーバーにリクエストして同期的に遷移したときも、reactアプリケーションのルーティングに従ってページを表示したい。

解決方法

  1. 参考ページにならって、build/_redirectsファイルを作成し、以下の通り記述します。
    /* /index.html 200
  2. デプロイし直します。

react 17.0.2 + storybook 6.4.9 でstorybookをビルドしてみる

参考にさせていただいたページ

create react-appについて

storybookについて

今回使用したバージョン

  • macOS Catalina 10.15.7
  • node v16.13.1
  • react 17.0.2
  • storybook 6.4.9 for React

create react-appする

TypeScriptを使うので以下のコマンドでcreate react-appしました。

yarn create react-app my-app --template typescript

cdする

cd my-app

一旦react-appを起動してみる

yarn start

storybookをインストールする

npx sb init

storybookを起動してみる

yarn storybook

おわりに

とりあえず最初はこれで動くはずです。

あとは実際に開発しながら追々やっていこうと思います。

create-react-appが失敗する問題に対処した「You are running `create-react-app` 4.0.3, which is behind the latest release (5.0.0). 」

参考にさせていただいたページ

失敗した操作

公式ページの「https://ja.reactjs.org/docs/create-a-new-react-app.html」にならって、以下のコマンドを実行しました。

npx create-react-app@latest my-app

すると以下のようなメッセージが表示されて、失敗しました。

You are running `create-react-app` 4.0.3, which is behind the latest release (5.0.0).

We no longer support global installation of Create React App.

Please remove any global installs with one of the following commands:
- npm uninstall -g create-react-app
- yarn global remove create-react-app

The latest instructions for creating a new app can be found here:
https://create-react-app.dev/docs/getting-started/

標示された通りに以下のコマンドを実行してから、create-react-appしなおしても駄目でした。

yarn global remove create-react-app

バージョンを指定して実行する

"npx create-react-app my-app" stopped working in 4.0.3 · Issue #10601 · facebook/create-react-app · GitHub」にある通り、以下のように最新バージョンを指定して実行したら正常に完了しました。

npx create-react-app@latest my-app

create-react-appしたアプリケーションでscssを使おうと思ったときにnode-sassのインストールに失敗した

はじめに

create-react-appしてアプリケーションを作りました。

node v16.10.0を使っていて、node-sass v6.0.1をインストールしました。

すると以下のようなエラーメッセージが表示されました。

Failed to compile
./src/index.scss (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-6-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref--5-oneOf-6-3!./node_modules/sass-loader/dist/cjs.js??ref--5-oneOf-6-4!./src/index.scss)
Node Sass version 6.0.1 is incompatible with ^4.0.0 || ^5.0.0.

一度removeしてインストールしようとしたら失敗

一度removeします。

yarn remove node-sass

ディレクトリを削除します。

rm -rf node_modules/node-sass

node-sass 5.0.0をインストールしようとしました。

yarn add node-sass@5.0.0

makeに失敗して以下のようなエラーが出ました。

1 error generated.
make: *** [Release/obj.target/binding/src/binding.o] Error 1
gyp ERR! build error 
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/path/to/your/app/node_modules/node-gyp/lib/build.js:262:23)
gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)
gyp ERR! System Darwin 19.6.0
gyp ERR! command "/Users/you/.nodebrew/node/v16.10.0/bin/node" "/path/to/your/app/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd /path/to/your/app/node_modules/node-sass
gyp ERR! node -v v16.10.0

nodeのバージョンを下げて再実行したら成功しました

nodeのバージョンをv16.10.0から、v15.6.0に下げて同じコマンドを実行しました。

一度removeします。

yarn remove node-sass

ディレクトリを削除します。

rm -rf node_modules/node-sass

node-sass 5.0.0をインストールします。

yarn add node-sass@5.0.0

node-sass@5.0.0 のインストールに成功しました。

2021年10月06日時点です。

nodeのバージョンは適宜調整されたら良いと思います。

ReactのeventHandler関数の型を定義する

参考にさせていただいたページ

型定義と関数定義を別々にやる

たぶんこんな感じ

import { FocusEventHandler, ChangeEventHandler, CompositionEventHandler } from 'react';

type HandleBlur = FocusEventHandler<HTMLInputElement>;
type HandleChange = ChangeEventHandler<HTMLInputElement>;
type HandleComposition = CompositionEventHandler<HTMLInputElement>;

const handleBlur: HandleBlur = ({ target, type }) => {
  console.log(target);
  console.log(type);
};

const handleChange: HandleChange = ({ target, type }) => {
  console.log(target);
  console.log(type);
};

const handleComposition: HandleComposition = ({ target, type }) => {
  console.log(target);
  console.log(type);
};

関数定義するときに引数の型設定をまとめてやる

たぶんこんな感じ

import { CompositionEvent } from 'react';

const handleComposition = ({
  target,
  type,
}: CompositionEvent<HTMLInputElement>) => {
  void onChange({ target, type });
};

Reactのchildrenにpropsを渡す

参考にさせていただいたページ

サンプルコード

import { cloneElement, Children, ReactElement } from 'react';

const HogeExample: React.FC = ({ children }) => {
  const additionalProps = { hoge: 'hoge' };

  const childrenWithAdditionalProps = Children.map(children, (child) => {
    switch (typeof child) {
      case 'string':
        // 子要素がテキストノードだった場合はそのまま return
        return child;

      case 'object':
        // React要素だった場合は newProps を渡す
        return cloneElement(child as ReactElement<any>, additionalProps);

      default:
        // それ以外の場合はとりあえず null 返しとく
        return null;
    }
  });

  return <form>{childrenWithAdditionalProps}</form>;
};

export default HogeExample;

サンプルコードのchildの型について

そのままだとエラーになっていたため、「 reactjs - How to assign the correct typing to React.cloneElement when giving properties to children? - Stack Overflow 」を参考に return cloneElement(child as ReactElement<any>, additionalProps); としています。