Introduction
In this lab, we will learn how to create a spinning loader component using React and CSS. The purpose of this component is to provide a visual indication to the user that the application is loading or processing data. By the end of this lab, you will have a reusable loader component that you can use in your React projects.
Spinning Loader
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
Renders a spinning loader component.
To render a spinning loader component, follow these steps:
- Render an SVG element whose dimensions are determined by the
sizeprop. - Use CSS to animate the SVG, creating a spinning animation. Specifically, add the
.loaderclass to the SVG and set theanimationproperty torotate 2s linear infinite. Also, define therotatekeyframes with atransformproperty that rotates the SVG 360 degrees. - Add a
circleelement to the SVG, which represents the spinning circle. To animate the circle, add the.loader circleselector and set theanimationproperty todash 1.5s ease-in-out infinite. Also, define thedashkeyframes withstroke-dasharrayandstroke-dashoffsetproperties that create a dashed stroke pattern that moves around the circle. - Finally, create a
Loadercomponent that renders the SVG with thesizeprop passed in as the width and height attributes.
.loader {
animation: rotate 2s linear infinite;
}
@keyframes rotate {
100% {
transform: rotate(360deg);
}
}
.loader circle {
animation: dash 1.5s ease-in-out infinite;
}
@keyframes dash {
0% {
stroke-dasharray: 1, 150;
stroke-dashoffset: 0;
}
50% {
stroke-dasharray: 90, 150;
stroke-dashoffset: -35;
}
100% {
stroke-dasharray: 90, 150;
stroke-dashoffset: -124;
}
}
const Loader = ({ size }) => {
return (
<svg
className="loader"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="12" cy="12" r="10" />
</svg>
);
};
To use the Loader component with a size of 24, call ReactDOM.createRoot(document.getElementById('root')).render(<Loader size={24} />);.
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the Spinning Loader lab. You can practice more labs in LabEx to improve your skills.