Finally, implement a busy indicator in the page by following the next steps:
- Implement the Busy component's behavior by creating this file and adding the following JavaScript code:
/src/components/common/Busy/Busy.js
import React from 'react';
import './Busy.css';
const Busy = () => (
<div className="busy-loader-container">
<div className="busy-loader"></div>
</div>
);
export default Busy;
- Implement Busy component styles by creating this file and adding the following CSS styles:
/src/components/common/Busy/Busy.css
.busy-loader-container {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
background-color: azure;
opacity: 0.5;
display: flex;
align-items: center;
justify-content: center;
}
.busy-loader {
border: 16px solid #f3f3f3;
border-top: 16px solid #3498db;
border-radius: 50%;
width: 80px;
height: 80px;
animation: busy-spin 2s linear infinite;
}
@keyframes busy-spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
- Re-export the Busy component by writing the following in /src/components/common/index.js:
import Header from './Header/Header';
import Busy from './Busy/Busy';
export {
Header,
Busy,
};
- Modify the ProductsPage component:
- Add a busy property set to false as the default starting state
- Change to the busy state when loading data is initiated and completed
- Render the Busy component if the busy state is true:
import React from 'react';
import MarketService from
'../../../services/marketService';
import {CategoryMenu, ProductList} from '../';
import {Busy} from '../../common';
class ProductsPage extends React.Component {
state = {
categories: [],
products: [],
busy: false,
};
componentDidMount() {
this.setState({busy: true});
this.loadCategoriesWhileBusy();
}
async loadCategoriesWhileBusy() {
try {
const categories = await
MarketService.loadCategories();
this.setState({
categories,
busy: false,
});
} catch (e) {
this.setState({busy: false});
throw e; // consider implementing actual error
handling
}
}
onCategoryChanged = (category) => {
this.setState({busy: true});
this.loadProductsWhileBusy(category);
}
async loadProductsWhileBusy(category) {
try {
const products = await
MarketService.loadProducts(category.name);
this.setState({
products,
busy: false,
});
} catch (e) {
this.setState({busy: false});
throw e; // consider implementing actual error
handling
}
}
render() {
return (
<div>
<CategoryMenu
categories={this.state.categories}
onCategoryChanged={this.onCategoryChanged}
/>
<ProductList products={this.state.products} />
{this.state.busy && <Busy />}
</div>
);
}
}
export default ProductsPage;
Congratulations! You have just completed the busy indicator, and with that, the page's functionality, in this chapter.