Reactとstyled-componentsを使ってローディング作成
ゴール
ブラウザでhttp://localhost:8111
にアクセスすると、左から右に動く「Loading」が表示できる
前提
「Hello World」が表示できる環境からスタート
使用するライブラリ
- styled-reset
- styled-components
手順
① ライブラリをインストール
yarn add styled-reset
yarn add styled-components
yarn add -D @types/styled-components
② 既存ファイルの編集
app.tsxにコードを追加
今回は、Reactで使えるリセットCSSを使用
※デバイスやブラウザによってデフォルトのスタイリングがついてしまうので、忘れないためにも記載
import React from "react";
import { Reset } from "styled-reset";
const App = () => {
return (
<>
<Reset />
<h1>Hello World</h1>
</>
);
};
export default App;
styled-componentsを使用
– <h1>
→ <StyledHello>
(自分で命名)
- styled.
の後に要素を指定
– バッククウォートで囲った中にCSSを記入
import React from "react";
import { Reset } from "styled-reset";
import styled from "styled-components";
const App = () => {
return (
<>
<Reset />
<StyledHello>Hello World</StyledHello>
</>
);
};
export default App;
const StyledHello = styled.h1`
font-size: 50px;
text-align: center;
`;
③ 確認①
yarn start
上記コマンドを実行し、ブラウザでhttp://localhost:8111
にアクセス
「Hello World
」が真ん中に表示されていたらOK!
④ ローディングを作成
下記、コードに変更
keyframesとopacityで動いているように見せる
import React from "react";
import { Reset } from "styled-reset";
import styled, { keyframes } from "styled-components";
const App = () => {
return (
<>
<Reset />
<StyledHello>Hello World</StyledHello>
<Load>Loading</Load>
</>
);
};
export default App;
const StyledHello = styled.h1`
font-size: 50px;
text-align: center;
`;
const opacityLoad = keyframes`
0% {
left: 0;
opacity: 0;
}
10% {
left: 10%;
opacity: 0.5;
}
30% {
left: 30%;
opacity: 1;
}
50% {
left: 50%;
opacity: 1;
}
70% {
left: 70%;
opacity: 0;
}
100% {
left: 100%;
opacity: 0;
}
`;
const Load = styled.p`
animation: ${opacityLoad} 2.3s linear infinite;
font-size: 50px;
position: relative;
width: 300px;
`;
⑤ 確認
yarn start
別ターミナルで上記コマンドを実行し、ブラウザでhttp://localhost:8111
にアクセス
左から右に動く「Loading」が表示されていればOK!
ディスカッション
コメント一覧
まだ、コメントがありません