I am trying to make the loading bar in the top of page when its loaded. How can I do that? I have no clue on how to do it and make it dynamic when the page is loaded.
CodePudding user response:
You can set a state as this:
const [isLoading, setIsLoading] = useState(true);
Then, you can show a loading bar in JSX defaultly:
<span style={isLoading ? {display: 'block'} : {display: 'none'}}>
Loading...
</span>
After, you can find out when the component has been loaded by using useEffect and square brackets:
useEffect(() => {
setIsLoading(false);
}, []);
That's it! When the component was loaded, the isLoading is set to false and loading bar is not shown anymore.
CodePudding user response:
You can set a LoadingState that will Show LoadingScreen until data is fetched and once fetched it will Show relevant Data.
function App() {
const [laoding, setLoading] = React.useState(true);
}
React.useEffect(() => {
fetchYourDataHere().
setLoading(false)
// This get called every time components Load
// Once we have our data we can set loading to false
},[depsHere])
if(loading) {
return <LoadingScreen />
}
return (<div> Your Regular Component </div>)
UseEffect is a Hook that can be used to fetch data at Every Component load. call your data fetching function in this and then set Loading State as False.
