How to useConditional Rendering in ReactJS
Example : This example uses Conditional Rendering to determine what to display based on the value of the loading state variable. When the button of Load Data is been clicked, the loading state is set to true, which causes the Spinner to be displayed.
Javascript
import "bootstrap/dist/css/bootstrap.min.css" ; import React, { useState, useEffect } from "react" ; import "bootstrap/dist/css/bootstrap.css" ; import { Spinner, Button, Container } from "react-bootstrap" ; function App() { const [loading, setLoading] = useState( false ); const [data, setData] = useState([]); useEffect(() => { const fetchData = async () => { setTimeout(() => { setData([ "Company Profile and Brand:" , "w3wiki is a leading platform..." , ]); setLoading( false ); }, 2000); }; if (loading) { fetchData(); } }, [loading]); return ( <Container className= "mt-4" > { " " } <div className= "jumbotron text-center bg-light" > { " " } <h1 className= "text-success" > w3wiki </h1> { " " } <p> Using Conditional Rendering </p> { " " } <Button variant= "primary" onClick={() => setLoading( true )} disabled={loading}> { " " } {loading ? "Loading..." : "Load Data" } { " " } </Button> { " " } </div>{ " " } {loading ? ( <div className= "text-center mt-4" > { " " } <Spinner animation= "border" role= "status" > { " " } <span className= "visually-hidden" > Loading... </span> { " " } </Spinner>{ " " } </div> ) : ( data.length > 0 && ( <ul className= "list-group mt-4" > { " " } {data.map((item, index) => ( <li key={index} className= "list-group-item" > { " " } {item} { " " } </li> ))}{ " " } </ul> ) )} { " " } </Container> ); } export default App; |
Output:
How to add Spinner while render a component on react-bootstrap?
In this article, we will add Spinner while rendering a component with the help of react-bootstrap. In the react web application, we can enhance the user experience by adding a Spinner styling component from the react-bootstrap library.
The two ways to add a spinner while rendering are discussed below:
Table of Content
- Using Promises
- Using Conditional Rendering