Adding Preloader in React Application - javascript

I want add a preloader in my react application. The reason is, my application needs much time to load. So, I want that When all my application contents is fully ready to be load, it will be rendered automatically. A preloader will be rendering as long as my application takes time to get ready to be loaded. Is it possible to do?
I need help.
This is me App code given below:-
import React from 'react';
import Navbar from './Navbar'
import Home from './Home';
import About from './About';
import Services from './Services';
import Skills from './Skills';
import Contact from './Contact';
import Footer from './Footer';
import Reset from './Reset';
function App() {
return (
<>
<Reset />
<Navbar />
<Home />
<About />
<Services />
<Skills />
<Contact />
<Footer />
</>
);
}
export default App;
This is my Index.js code given below:-
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Preloader from './Preloader'
ReactDOM.render(
<App/>
,document.getElementById('root')
);

Depending on what you want to achieve you have many options on doing this. That is the goal of using frameworks like React.
My advice is, separate the loading of data( API calls etc.) from the loading of UI. Use async methods for loading the data where you can do that. I see that you are using functional components, so look into react hooks and generating the data using states.
You have a way of setting a default value to a state so everything could render independently from the data generation. Later when the state is set to your data the site will render automatically with the new data.
Specifically to setting a preload ui you can check this post:
React - Display loading screen while DOM is rendering?

We usually make an API call and until the data is ready we show a loader. An SVG Loader or any other loader.
You basically need to set three states to maintain loading, error and your data:
Use the following setup this will be helpful in your project. Also visit my github project to get Loader Code from API and Loader
function App() {
const [tours, setTours] = useState([]);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
/*--- I am using fetch API here
useEffect(() => {
setLoading(true);
fetch(url)
.then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw new Error("Could not fetch data");
}
})
.then((tours) => {
setLoading(false);
setTours(tours);
})
.catch((err) => console.log(err));
}, []);
---*/
const fetchTours = async () => {
try {
const response = await fetch(url);
const tours = await response.json();
setLoading(false);
setTours(tours);
} catch (error) {
setLoading(false);
setError(true);
}
};
useState(() => {
setLoading(true);
fetchTours();
}, []);
// Functionality 1: Not Interested Button click
const handleBtnClick = (id) => {
const updatedTours = tours.filter((tour) => tour.id !== id);
setTours(updatedTours);
};
// Functionality 2: Refresh Button click
const handleRefresh = () => {
setLoading(true);
fetchTours();
};
// Let us do conditional rendering
if (loading) {
return (
<div style={{ textAlign: "center", margin: "2rem 0" }}>
<Loader />
</div>
);
}
if (error) {
return <p>Error ...</p>;
}
return (
<section>
<p className="our-tours">
{tours.length > 0 ? (
"Our Tours"
) : (
<div>
<p>No Tours Left</p>
<button className="btn" onClick={handleRefresh}>
Refresh
</button>
</div>
)}{" "}
</p>
<main className="App">
{tours.length > 0 && (
<Tours tours={tours} handleClick={handleBtnClick} />
)}
</main>
</section>
);
}
export default App;
There are three scenarios:
Initially our loading is true and we show our loader.
When the data has successfully arrived, we start showing the data and hide our Loader.
When there is an error in our API call, we show the error message.
The above setup works in all cases :)

If you're using reactjs, you need to make a component so try this:
import { useEffect } from "react";
import { Rings } from "react-loader-spinner";
const Loader = () => {
useEffect(() => {
window.onload=()=>{
const preloader = document.querySelector(".preloader");
preloader.remove();
}
});
return <LoaderFile/>
// which have your preloader html and having class is `.preloader`
};
export default Loader;
In App.js File
const App = () => {
return (
<>
<Loader /> // Add Loader Component here
<Router>
<Routes>
<Route path="/" element={<Navigation />}>
<Route index element={<Main />} />
</Route>
</Routes>
</Router>
</>
);
};

Related

React not getting API results on first render

I'm running into a problem in development where the page finishes loading before the data gets sent from the API. I've tried using asynchronous functions but that doesn't help even though I'm sure it should. I think I might be doing it wrong. Below is an example of a page in my app where I am experiencing this issue:
import React, {useEffect, useState} from 'react';
import { useRouter } from 'next/router';
import axios from 'axios';
import Link from 'next/link';
import { Card,
Button
} from 'react-bootstrap';
export default function SingleTour() {
const [tour, setTour]= useState({});
const [tourShows, setTourShows] = useState({});
const router = useRouter();
const {slug} = router.query;
useEffect( () => {
let enpoints = [
`http://localhost:3000/tours/${slug}`,
`http://localhost:3000/listshows/${slug}`
]
axios.all(
enpoints.map((endpoint) =>
axios.get(endpoint)))
.then(response => {
console.log(response)
setTour(response[0].data)
setTourShows(response[1].data)
})
.catch(error => console.log(error))
}, [slug])
console.log(tour);
return (
<div className='container'>
<div>
<h1></h1>
</div>
<h3>Shows</h3>
<div className='card-display'>
{tourShows.data ? (
tourShows.data.map(({attributes, id}) => (
<Link href={`/shows/${id}`} passHref key={id}>
<Card border="secondary" style={{ width: '18rem', margin: '1rem'}}>
<Card.Body>
<Card.Title>Show {id}</Card.Title>
<Card.Text>{attributes.date}</Card.Text>
<Card.Text>{attributes.location}</Card.Text>
<Card.Text>Head Count {attributes.headcount}</Card.Text>
</Card.Body>
</Card>
</Link>
))
) : 'LOADING ...'}
</div>
</div>
)
}
Any help is greatly appreciated. I am also using Next JS if that makes a difference.
If you use useEffect hook it is expected that you will have a render before the hook fires to fetch the data, that is the way useEffect works.
If you want to fetch your data inside the next app you have to use getServerSideProps instead, fetch the data there and pass that as a prop to the component. See the docs here: https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props
This is the way React works. useEffect will attempt to fetch the data and React will continue doing it's business, render the component. You can put an if statement at the beginning of the return statement, for instance checking the length of the tourShows.data, it the length is 0 return nothing, otherwise return as you do now.

Show a skeleton placeholder until Facebook Comments component loads completely in React (Next.js)

Using Next.js, I want to show a skeleton placeholder until Facebook Comments component loads completely.
Here is the code.
import { useState, useEffect } from "react";
import { initFacebook } from "../utils/initFacebook";
export default function IndexPage() {
const [loaded, setLoaded] = useState(false);
useEffect(() => {
const loadFacebook = async () => {
await initFacebook();
setLoaded(true);
};
loadFacebook();
}, []);
const skeletonComponent = (
<div>
<h1>Some skeleton placeholder</h1>
</div>
);
const facebookComponent = (
<div
className="fb-comments"
data-href="https://developers.facebook.com/docs/plugins/comments#configurator"
data-width="580"
data-numposts="10"
/>
);
return (
<div>
{loaded ? facebookComponent : skeletonComponent}
</div>
);
}
I'm using the state to switch between two components.
But the skeleton component does not wait until the Facebook component is fully loaded, and therefore users see the blank screen for about 3-5 seconds.
How should I go about having the skeleton component wait out until the Facebook component is visible?
The full code is available on CodeSandbox.
Any help would be appreciated.

How to work with setInterval to trigger an event? JavaScript/React-toastify

I have a redux store that contains an object that looks like
rooms: {
room01 : { timestamp: 10}
room02 : { timestamp: 10}
}
When a user clicks on a button the timestamp is set to 10 (via dispatch). If there is a timestamp I count down to 0 and then set a Notification using react-toast across the app.
The problem is I don't have roomId available on Notification component because Notification component has to be placed at app root otherwise it's get unmounted and my Notification() logic doesn't work. (I could access the rooms in Notification or App but it comes in an array for eg ['room01', 'room02'] which is also in redux but how do I select both rooms and access their timestamp as well as run the function to count down?).
Basically I need to check if there is timestamp in redux store for each room and if there is, count down to 0 and display notification with the roomId. The notification/setinterval should work while navigating to different pages.
My app component
import React from 'react';
import { Route, Switch, BrowserRouter } from 'react-router-dom';
import Home from './Home';
import 'react-toastify/dist/ReactToastify.css';
import Notification from '../features/seclusion/Notification';
const App = () => {
return (
<div>
<Notification /> // if I pass in room id like so roomId={'room02'} I cant get it to work for one room
<BrowserRouter>
<Switch>
<Route exact path="/room/:id" component={Room} />
<Route exact path="/" component={Home} />
</Switch>
</BrowserRouter>
</div>);
};
export default App;
import React, { useState, useEffect } from 'react';
import { useSelector } from 'react-redux';
import 'react-toastify/dist/ReactToastify.css';
import { ToastContainer, toast, Slide } from 'react-toastify';
import moment from 'moment';
export default function Notification() {
const timestamp = useSelector(state => state.rooms); // need to get timestamp for room01 and room02
const [timestamp, setTimestamp] = useState(null);
const [timerId, setTimerId] = useState(null);
const notify = () => {
toast(<div>alert</div>,
{
position: "top-center",
});
};
useEffect(() => {
if (timestamp) {
const id = setInterval(() => {
setTimestamp((timestamp) => timestamp - 1)
}, 1000)
setTimerId(id);
}
return () => {
clearInterval(timerId);
};
}, [timestamp]);
useEffect(() => {
if(timestamp === 0){
notify();
clearInterval(timerId);
}
}, [timestamp])
return (
<ToastContainer
newestOnTop={true}
transition={Slide}
autoClose={false}
/>
);
}
You could do the following among other approaches, but i think the following is the best because it makes the Notification component more reusable, and also it makes better use of the separation of responsibilities, makes your code easier to read, and most importantly is aligned with the declarative mindset of React.
const App = () => {
const rooms = state.rooms // this is not redux syntax but i will leave that to you
return (
<div>
{Object.entries(rooms).map(([roomId, roomDetails]) => {
const {timestamp} = roomDetails;
// Obviously you now need to modify your Notification component to handle these props
return <Notification
timestamp={timestamp}
roomId={roomId} // actually its better to create the Notification component without the roomId prop and use the roomId to induce the message prop, this makes Notification component more reusable across other components
key={`${roomId}-${timestamp}`}
message="You might send message here instead of doing that inside the Notification component"
/>
// You might be interested to rename Notification to DelayedNotification or something else
}}
<BrowserRouter>
<Switch>
<Route exact path="/room/:id" component={Room} />
<Route exact path="/" component={Home} />
</Switch>
</BrowserRouter>
</div>);
};

testing routing capabilities of preact-router

How would I be able to test the router in the code below? When using React you are able to use MemoryRouter to pass initialEntries to mock a route change but I cannot find an alternative for preact-router. I looked at the Preact docs and the preact-router docs but I am unable to find a clear solution.
import 'preact/debug';
import { h, render } from 'preact';
import HomePage from './pages/homepage';
import Router from 'preact-router';
import AsyncRoute from 'preact-async-route';
import './styles/index.scss';
const App = () => (
<Router>
<HomePage path="/" />
<AsyncRoute
path="/admin"
getComponent={ () => import('./pages/admin').then(module => module.default) }
/>
</Router>
);
export default App;
This is a little old, but I figured I would share what I found.
The first and quickest thing to do is to just use the route function in preact-router.
import { render, route } from 'preact-router';
import App from './App';
describe('<App/>', () => {
it('renders admin', async () => {
const { container, findByText } = render(<App/>);
// Go to admin page
route('/admin');
// Wait for page to load since it's loaded async
await findByText(/Admin Page/);
// perform expectations.
});
});
While this works, I don't like that it relies on the brower's real history. Luckily, the <Router> component accepts a history prop of type CustomHistory. So you can use an in-memory implementation of a History API to make this happen. I think I've seen docs that suggest using the history package - however I had to make an adjustment
import { createMemoryHistory } from 'history';
class MemoryCustomHistory {
constructor(initialEntries = undefined) {
this.wrapped = createMemoryHistory({initialEntries});
}
get location() {
return this.wrapped.location;
}
// Listen APIs not quite compatible out of the box.
listen(callback) {
return this.wrapped.listen((locState) => callback(locState.location));
}
push(path) {
this.wrapped.push(path);
}
replace(path) {
this.wrapped.replace(path);
}
}
Next, update your app to accept a history property to pass to the <Router>
const App = ({history = undefined} = {}) => (
<Router history={history}>
<HomePage path="/" />
<AsyncRoute
path="/admin"
getComponent={ () => import('./pages/admin').then(module => module.default) }
/>
</Router>
);
Finally, just update the tests to wire your custom history to the app.
it('renders admin', async () => {
const history = new MemoryCustomHistory(['/admin]);
const { container, findByText } = render(<App history={history}/>);
// Wait for page to load since it's loaded async
await findByText(/Admin Page/);
// perform expectations.
});

How can I change this class base higher order component into a functional component?

I have already created a HOC in my react app following this, and its working fine. However i was wondering if there is a way to create a HOC as functional component(With or without state)??? since the given example is a class based component.
Tried to find the same over web but couldn't get anything. Not sure if thats even possible?? Or right thing to do ever??
Any leads will be appreciated :)
I agree with siraj, strictly speaking the example in the accepted answer is not a true HOC. The distinguishing feature of a HOC is that it returns a component, whereas the PrivateRoute component in the accepted answer is a component itself. So while it accomplishes what it set out to do just fine, I don't think it is a great example of a HOC.
In the functional component world, the most basic HOC would look like this:
const withNothing = Component => ({ ...props }) => (
<Component {...props} />
);
Calling withNothing returns another component (not an instance, that's the main difference), which can then be used just like a regular component:
const ComponentWithNothing = withNothing(Component);
const instance = <ComponentWithNothing someProp="test" />;
One way to use this is if you want to use ad-hoc (no pun intended lol) context providers.
Let's say my application has multiple points where a user can login. I don't want to copy the login logic (API calls and success/error messages) across all these points, so I'd like a reusable <Login /> component. However, in my case all these points of login differ significantly visually, so a reusable component is not an option. What I need is a reusable <WithLogin /> component, which would provide its children with all the necessary functionality - the API call and success/error messages. Here's one way to do this:
// This context will only hold the `login` method.
// Calling this method will invoke all the required logic.
const LoginContext = React.createContext();
LoginContext.displayName = "Login";
// This "HOC" (not a true HOC yet) should take care of
// all the reusable logic - API calls and messages.
// This will allow me to pass different layouts as children.
const WithLogin = ({ children }) => {
const [popup, setPopup] = useState(null);
const doLogin = useCallback(
(email, password) =>
callLoginAPI(email, password).then(
() => {
setPopup({
message: "Success"
});
},
() => {
setPopup({
error: true,
message: "Failure"
});
}
),
[setPopup]
);
return (
<LoginContext.Provider value={doLogin}>
{children}
{popup ? (
<Modal
error={popup.error}
message={popup.message}
onClose={() => setPopup(null)}
/>
) : null}
</LoginContext.Provider>
);
};
// This is my main component. It is very neat and simple
// because all the technical bits are inside WithLogin.
const MyComponent = () => {
const login = useContext(LoginContext);
const doLogin = useCallback(() => {
login("a#b.c", "password");
}, [login]);
return (
<WithLogin>
<button type="button" onClick={doLogin}>
Login!
</button>
</WithLogin>
);
};
Unfortunately, this does not work because LoginContext.Provider is instantiated inside MyComponent, and so useContext(LoginContext) returns nothing.
HOC to the rescue! What if I added a tiny middleman:
const withLogin = Component => ({ ...props }) => (
<WithLogin>
<Component {...props} />
</WithLogin>
);
And then:
const MyComponent = () => {
const login = useContext(LoginContext);
const doLogin = useCallback(() => {
login("a#b.c", "password");
}, [login]);
return (
<button type="button" onClick={doLogin}>
Login!
</button>
);
};
const MyComponentWithLogin = withLogin(MyComponent);
Bam! MyComponentWithLogin will now work as expected.
This may well not be the best way to approach this particular situation, but I kinda like it.
And yes, it really is just an extra function call, nothing more! According to the official guide:
HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.
Definitely you can create a functional stateless component that accepts component as an input and return some other component as an output, for example;
You can create a PrivateRoute component that accepts a Component as a prop value and returns some other Component depending on if user is authenticated or not.
If user is not authenticated(read it from context store) then you redirect user to login page with <Redirect to='/login'/>else you return the component passed as a prop and send other props to that component <Component {...props} />
App.js
const App = () => {
return (
<Switch>
<PrivateRoute exact path='/' component={Home} />
<Route exact path='/about' component={About} />
<Route exact path='/login' component={Login} />
<Route exact path='/register' component={Register} />
</Switch>
);
}
export default App;
PrivateRoute.jsx
import React, { useContext , useEffect} from 'react';
import { Route, Redirect } from 'react-router-dom'
import AuthContext from '../../context/auth/authContext'
const PrivateRoute = ({ component: Component, ...rest }) => {
const authContext = useContext(AuthContext)
const { loadUser, isAuthenticated } = authContext
useEffect(() => {
loadUser()
// eslint-disable-next-line
}, [])
if(isAuthenticated === null){
return <></>
}
return (
<Route {...rest} render={props =>
!isAuthenticated ? (
<Redirect to='/login'/>
) : (
<Component {...props} />
)
}
/>
);
};
export default PrivateRoute;
Higher Order Components does not have to be class components, their purpose is to take a Component as an input and return a component as an output according to some logic.
The following is an over simplified example of using HOC with functional components.
The functional component to be "wrapped":
import React from 'react'
import withClasses from '../withClasses'
const ToBeWrappedByHOC = () => {
return (
<div>
<p>I'm wrapped by a higher order component</p>
</div>
)
}
export default withClasses(ToBeWrappedByHOC, "myClassName");
The Higher Order Component:
import React from 'react'
const withClasses = (WrappedComponent, classes) => {
return (props) => (
<div className={classes}>
<WrappedComponent {...props} />
</div>
);
};
export default withClasses;
The component can be used in a different component like so.
<ToBeWrappedByHOC/>
I might be late to the party but here is my two-cent regarding the HOC
Creating HOC in a true react functional component way is kind of impossible because it is suggested not to call hook inside a nested function.
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you’re curious, we’ll explain this in-depth below.)
Rules of Hooks
Here is what I have tried and failed
import React, { useState } from "react";
import "./styles.css";
function Component(props) {
console.log(props);
return (
<div>
<h2> Component Count {props.count}</h2>
<button onClick={props.handleClick}>Click</button>
</div>
);
}
function Component1(props) {
console.log(props);
return (
<div>
<h2> Component1 Count {props.count}</h2>
<button onClick={props.handleClick}>Click</button>
</div>
);
}
function HOC(WrapperFunction) {
return function (props) {
const handleClick = () => {
setCount(count + 1);
};
const [count, setCount] = useState(0);
return (
<WrapperFunction handleClick={handleClick} count={count} {...props} />
);
}
}
const Comp1 = HOC((props) => {
return <Component {...props} />;
});
const Comp2 = HOC((props) => {
return <Component1 {...props} />;
});
export default function App() {
return (
<div className="App">
<Comp1 name="hel" />
<Comp2 />
</div>
);
}
CodeSandBox
Even though the code works in codesandbox but it won't run in your local machine because of the above rule, you should get the following error if you try to run this code
React Hook "useState" cannot be called inside a callback
So to go around this I have done the following
import "./styles.css";
import * as React from "react";
//macbook
function Company(props) {
return (
<>
<h1>Company</h1>
<p>{props.count}</p>
<button onClick={() => props.increment()}>increment</button>
</>
);
}
function Developer(props) {
return (
<>
<h1>Developer</h1>
<p>{props.count}</p>
<button onClick={() => props.increment()}>increment</button>
</>
);
}
//decorator
function HOC(Component) {
// return function () {
// const [data, setData] = React.useState();
// return <Component />;
// };
class Wrapper extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<Component count={this.state.count} increment={this.handleClick} />
);
}
}
return Wrapper;
}
const NewCompany = HOC(Company);
const NewDeveloper = HOC(Developer);
export default function App() {
return (
<div className="App">
<NewCompany name={"Google"} />
<br />
<NewDeveloper />
</div>
);
}
CodeSandbox
I think for functional component this works fine
import {useEffect, useState} from 'react';
// Target Component
function Clock({ time }) {
return <h1>{time}</h1>
}
// HOC
function app(C) {
return (props) => {
const [time, setTime] = useState(new Date().toUTCString());
useEffect(() => {
setTimeout(() => setTime(new Date().toUTCString()), 1000);
})
return <C {...props} time={time}/>
}
}
export default app(Clock);
You can test it here: https://codesandbox.io/s/hoc-s6kmnv
Yes it is possible
import React, { useState } from 'react';
const WrapperCounter = OldComponent =>{
function WrapperCounter(props){
const[count,SetCount] = useState(0)
const incrementCounter = ()=>{
SetCount(count+1)
}
return(<OldComponent {...props} count={count} incrementCounter={incrementCounter}></OldComponent>)
}
return WrapperCounter
}
export default WrapperCounter
import React from 'react';
import WrapperCounter from './WrapperCounter';
function CounterFn({count,incrementCounter}){
return(
<button onClick={incrementCounter}>Counter inside functiona component {count}</button>
)
}
export default WrapperCounter(CounterFn)

Categories