How to create a loading spinner in React?

To create a loading spinner in React, you can use CSS to style the spinner and then conditionally render it based on the loading state of your component. Here is an example of how you can create a simple loading spinner in React:

  1. Create a CSS file for styling the spinner. You can customize the styles of the spinner as needed:
.spinner { border: 4px solid rgba(0, 0, 0, 0.1); border-top: 4px solid #3498db; border-radius: 50%; width: 30px; height: 30px; animation: spin 1s linear infinite; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
  1. In your React component, add a state variable to track the loading state and conditionally render the spinner based on that state:
import React, { useState, useEffect } from 'react'; import './Spinner.css'; const Spinner = () => { const [loading, setLoading] = useState(true); useEffect(() => { // Simulate loading data setTimeout(() => { setLoading(false); }, 3000); }, []); return ( <div> {loading ? <div className="spinner"></div> : <p>Data loaded successfully!</p>} </div> ); } export default Spinner;

In this example, the Spinner component will display the spinner animation until the loading state is set to false. You can customize the spinner's appearance and loading logic according to your needs.