moving soon →kajiri.dev

gatsbyとtailwindcssでclassNameが再レンダリングされない

December 31, 2020

commit history
  1. 2020/12/27 22:36:40 014b342
headline

状況

import React from 'react';

...

const Index = () => {
  ...

  if (loading) {
    return (
      <div className="mb-20 mt-10">
        ...loading
      </div>
    )
  }
  return (
    <div>
      ...
    </div>
  )
}
export default Index

こんなかんじでコンポーネントを書いて、loadingが終了した時にclassNameのmb-20 mt-10が引き継がれていた。

なぜか

わかりませんでしたー

ただ、react公式をみるに、classNameの変更は検知してくれる

https://ja.reactjs.org/docs/reconciliation.html#dom-elements-of-the-same-type

で結局、divタグみたいな挙動をしてくれればよかったので、利用頻度の低そうなmainタグで代用しました

結果

import React from 'react';

...

const Index = () => {
  ...

  if (loading) {
    return (
      <main className="mb-20 mt-10">
        ...loading
      </main>
    )
  }
  return (
    <div>
      ...
    </div>
  )
}
export default Index

おまけ

たぶんreact, gatsby, tailwindcssあたりを見れば解決出来るんだろうけど、そこまでやる時間がありませんでした。とりあえずの解決策として上記が機能しました。

また、stackoverflowをみると、keyを書いて一意にすればいけるぜ!って書いてたんだけど今回は機能しませんでした。不思議

https://stackoverflow.com/questions/60339095/reactjs-re-render-is-not-applied-on-css/60339265#60339265


contact