LoginSignup
3
2

More than 1 year has passed since last update.

React + Styled-components(CSS )

Posted at

簡単な動きのあるローディング作成

以前作成した下記記事の環境からスタートします。

リセットCSS

import React from "react";
import { Reset } from "styled-reset";

const App = () => {
return (
    <>
    <Reset />
    <h1>Hello World</h1>
    </>
);
};
export default App;

yarn add styled-reset
今回は、Reactで使えるリセットCSSを使用
※デバイスやブラウザによってデフォルトのスタイリングがついてしまうので、忘れないためにも記載してます。

styled-components

yarn add styled-components @types/styled-components

app.tsx

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を実行しHello Worldが真ん中に表示されていたらOK!
- <h1> → <StyledHello>(自分で命名可能)
- styled.の後に要素を指定
- バッククウォートで囲った中にCSSを記入

ローディング

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を実行し、左から右に動くLoadingが出ていればOK!
- styled-componentsから{ keyframes }を追加(アニメーション)
- 透明度をopacityLoadに記載して、LoadopacityLoadを追加

最後に

styled-componentsを導入することで、HTMLとCSSの要素を1つのファイルで見れるのは、非常に管理しやすいです。また、HTML,CSSよりもクラス名などで困ることが少ないのもメリットかなと思います。

参考文献

3
2
0

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
3
2