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] Styleの設定方法

Posted at

環境

MacBook Pro (2.3 GHz 8コアIntel Core i9)
macOS 14.0(23A344)
Homebrew 4.3.8
gh 2.52.0

まとめ

  • React内にJavaScriptのスタイル用の関数を埋め込む
  • HTMLにJavaScriptコードを埋め込む際は{}を用いる
e.g.
export const App = () => {
  const onClickButton = () => alert();
  return (
    <>
+     <h1 style={{color: `red`}}>こんにちは!</h1>
      <p>お元気ですか?</p>
      <button onclick={onClickButton}>ボタン</button>
    </>
  );
};

フォルダ構成

folda_structure
├── public/
│   ├── index.html
└── src/
│   ├── index.js(index.jsx)
│   └── App.js(App.jsx)      

ソースコード

index.js
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

↓関数を外へ出し可読性を上げている

App.js
export const App = () => {
  const onClickButton = () => alert();
+ const contentStyleA ={
+   color: "red"
+ };
+ const contentStyleB ={
+   color: "blue"
+ };
  return (
    <>
+     <h1 style={contentStyleA}>こんにちは!</h1>
+     <p style={contentStyleB}>お元気ですか?</p>
      <button onclick={onClickButton}>ボタン</button>
    </>
  );
};

イメージ

image.png

参考リンク

0
0
1

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?