the first useEffect seems to contradict with my globeComponent: import { motion } from "framer-motion";
import React, { useState, useEffect } from "react";
import { useRouter } from "next/router";
import ParticlesContainer from "./ParticlesContainer";
import { useGlobe } from '../components/globe/globeContext';
useEffect(() => {
function handleResize() {
// Safeguarding window access
if (typeof window !== 'undefined') {
if (window.innerWidth < 768) {
setIsMobileView(true);
} else {
setIsMobileView(false);
}
}
}
// Since we're using window, we safeguard the entire effect
if (typeof window !== 'undefined') {
handleResize();
window.addEventListener('resize', handleResize);
}
useEffect(() => {
// If we're on the homepage and globe is ready, set loaded to true
if (router.pathname === '/' && globeReady) {
setIsLoaded(true);
} else if(router.pathname!== '/') {
setIsLoaded(true);
}
}, [globeReady, router.pathname]);
export default Transition;
GlobeComponent: import React, { useEffect, useState, useRef } from 'react';
import Globe from 'react-globe.gl';
import * as THREE from 'three';
import { useRouter } from 'next/router';
import { useGlobe } from '../components/globe/globeContext';
import countries from './files/globe-data-min.json';
import travelHistory from './files/my-flights.json';
import airportHistory from './files/my-airports.json';
The useEffect hook you've posted from the Transition component does not appear to contradict directly with the GlobeComponent. The possible perception of contradiction might be related to when and how the transition is triggered, more specifically, how the isLoaded state is determined.
Here's a breakdown of how both components use useEffect:
Transition Component
The first useEffect in the Transition component is used to add and remove a window resize event listener. This listener updates the isMobileView state when the window size changes.
The second useEffect listens for changes to globeReady and router.pathname. It sets isLoaded to true if either the homepage is loaded and the globe is ready or when the user navigates away from the homepage. This effect controls when to stop showing the transition/loading animation. It makes sure the loading animation is displayed until the necessary resources (like the globe in this case) are ready.
GlobeComponent
The first useEffect in GlobeComponent is responsible for adjusting the dimensions of the globe based on the window size.
The second useEffect ensures that the globe initially sets the point of view. Note that this effect lacks any dependencies and will only run once when the component is first mounted, which is likely not what was intended since it never triggers after the globeRef becomes valid. It may need dependencies, such as globeRef.current, to execute correctly.
Another useEffect in GlobeComponent sets up an event listener to respond to Next.js route changes, updating arcsData with new data when the event happens.
Possible Issues
If the setGlobeReady(true) function is only called inside the onGlobeReady callback in the GlobeComponent, and if for some reason, the globe takes more time to load or the onGlobeReady callback does not fire as expected, the isLoaded state in the Transition component might not be set to true due to its dependency on globeReady. This would mean the transition/loading animation continues to play indefinitely.
User
this is the exact issue i am facing: - If the setGlobeReady(true) function is only called inside the onGlobeReady callback in the GlobeComponent, and if for some reason, the globe takes more time to load or the onGlobeReady callback does not fire as expected, the isLoaded state in the Transition component might not be set to true due to its dependency on globeReady. This would mean the transition/loading animation continues to play indefinitely.
Assistant
If the setGlobeReady(true) call within the onGlobeReady callback of the GlobeComponent is not firing as expected, or there's a delay, then indeed isLoaded in the Transition component will not be set to true, causing the transition/loading animation to play indefinitely. Here are a couple of approaches to address this issue:
1. Debugging the onGlobeReady Callback
The first step is to determine why the callback is not firing. Add logging inside the onGlobeReady callback to see if it's called at all:
javascript
onGlobeReady={() => {
console.log('Globe is ready');
setGlobeReady(true);
}}
If the log statement doesn't appear in the console, then the onGlobeReady event might not be firing due to an issue with the react-globe.gl library or how it is integrated into your application.
2. Adding a Timeout Fallback
As a failsafe, you can add a timeout function that will set isLoaded to true after a certain amount of time, regardless of whether the onGlobeReady event has fired. This is a workaround to ensure that your application's loading state progresses:
javascript
// In the Transition component
useEffect(() => {
const timeoutId = setTimeout(() => {
setIsLoaded(true);
}, 10000); // Set a timeout for 10 seconds
return () => clearTimeout(timeoutId);
}, []);
// And retain the existing useEffect that listens to globeReady and pathname changes
This will guarantee that after 10 seconds, the application will consider the globe as ready, even if it isn't. This is a stopgap solution and you should investigate the root cause of the event not firing to find a proper solution.
3. Refactoring Transition Component Logic
If you have control over the GlobeComponent, consider adding another state called globeError or similar, which you can then use to signal the Transition component that the globe couldn't be loaded:
javascript
User
Module not found: Can't resolve '@tsparticles/react'
Assistant
The error message "Module not found: Can't resolve '@tsparticles/react'" indicates that your project is trying to import @tsparticles/react module, but the package manager (like npm or yarn) cannot find it in your node_modules directory. This usually means that the package hasn't been installed yet or there was an issue during installation.
To resolve this issue, you need to install the package via npm or yarn, which is responsible for the particle effects you may be trying to use. Here's how you can do it:
For npm, run the following command in your project's root directory:
sh
npm install @tsparticles/react
For yarn, use this command instead:
sh
yarn add @tsparticles/react
After the installation is complete, you should be able to import from @tsparticles/react without any issues.
In case you continue to face problems, here are a few things to check:
Correct Package Name: Ensure that you are using the correct package name in your import statement. It is case-sensitive and must match the name specified in your package.json file after installation.
Re-install Node Modules: It may also help to delete your node_modules folder and package-lock.json file (if using npm) or yarn.lock file (if using yarn), and then run npm install or yarn install again to ensure a clean slate.
Version Compatibility: Check that the version of @tsparticles/react you're installing is compatible with your project's React version.
Node/NPM/Yarn Version: Ensure you are using recent or stable versions of node, npm, or yarn. Sometimes, older versions might cause unexpected issues.
Project Configuration: Verify that your webpack configuration or whatever bundler you're using is set up correctly to resolve modules from your node_modules directory. Additionally, if your project supports TypeScript, check that the typings are resolved or available.
User
Module not found: Can't resolve '@tsparticles/slim'
Assistant
The error message "Module not found: Can't resolve '@tsparticles/slim'" is similar to the previous issue, where the package manager is unable to find the @tsparticles/slim module in your node_modules directory. This suggests that the @tsparticles/slim package has not been installed. The @tsparticles/slim package is likely a part of the tsParticles family that provides a slim version of the tsParticles library, which might contain only the core functionalities without additional plugins or shapes.
To fix this, you need to install the package using npm or yarn. As of my knowledge cutoff in April 2023, @tsparticles/slim might not be an official or existing package of the tsParticles ecosystem. So, if you have found this package name in a documentation or tutorial, it could be outdated or incorrect.
The official tsParticles package that you likely would want to use is tsparticles, which you can install with the following commands:
If you are certain @tsparticles/slim is the correct package, the approach to install it would be:
Using npm:
sh
npm install @tsparticles/slim
Using yarn:
sh
yarn add @tsparticles/slim
But since the package may not exist, or might be a part of a specific set of tsParticles packages, you might need to verify the source from which you got the package name and whether it's a custom build or a less common version of the library.
If none of these solutions work, I advise you to check the following:
Verify the source where you found @tsparticles/slim to make sure it's correct, and check for any typographical errors in the package name.
Check the official tsParticles repositories and npm registry for the correct package name and instructions.
Look up any custom or unofficial tsParticles builds that might use a different naming convention and ensure they are properly maintained and compatible with your project.
User
Despite the transitionDelay holding the loading page in place, the transiton still occurs before Globe is ready: import { motion } from "framer-motion";
import React, { useState, useEffect } from "react";
import { useRouter } from "next/router";
import ParticlesContainer from "./ParticlesContainer";
import { useGlobe } from '../components/globe/globeContext';
useEffect(() => {
function handleResize() {
// Safeguarding window access
if (typeof window !== 'undefined') {
if (window.innerWidth < 768) {
setIsMobileView(true);
} else {
setIsMobileView(false);
}
}
}
// Since we're using window, we safeguard the entire effect
if (typeof window !== 'undefined') {
handleResize();
window.addEventListener('resize', handleResize);
}
useEffect(() => {
// If we're on the homepage and globe is ready, set loaded to true
if (router.pathname === '/' && globeReady) {
setIsLoaded(true);
} else if(router.pathname!== '/') {
setIsLoaded(true);
}
}, [globeReady, router.pathname]);
The problem you're encountering seems to stem from the transition triggering independently of the globeReady state. From the code you've provided, transitionDelay is checked before the return statement, but it doesn't seem to connect directly with the animation logic. This means that even if transitionDelay is set to Infinity, the animation could still proceed regardless if the check isn't correctly influencing the transition.
Let's refactor the transition logic to depend directly on isLoaded. Since transitionDelay doesn't directly control the animation, instead of setting it to Infinity, we should use the isLoaded state to control whether the transition should occur.
You want to adjust the motion.div responsible for the transition to respond to changes in isLoaded. You can conditionally set the animate property based on isLoaded so that it only triggers the animation when isLoaded is true. Here's a possible refactor:
jsx
const transitionVariants = {
// ... unchanged
};
useEffect(() => {
// ... unchanged
}, []);
// Directly use `isLoaded` to control the visibility of the transition overlay
const shouldHideTransition = isLoaded || (router.pathname !== '/' && !globeReady);
return (
<>
{!shouldHideTransition && (
<motion.div
// ...
initial="initial"
animate={isLoaded ? "animate" : "initial"} // Only animate out if isLoaded is true
// ...
>
{/* ... */}
</motion.div>
)}
{/* Rest of your components */}
</>
);
With the code above, the initial transition animation will occur when the component mounts due to the initial state of isLoaded being false. As soon as isLoaded becomes true (either by the globe finishing loading or when moving away from the home page), the animate prop will switch to "animate", triggering the closing transition.
This approach requires the useEffect that sets isLoaded to be perfectly synchronized with the readiness of your . If there are discrepancies in when is set, the transition might still happen prematurely. It is essential to ensure is called at the appropriate time when the globe is fully loaded and ready to interact with. If this isn't reliable, consider implementing a timeout as a fallback mechanism, as mentioned previously.
User
My react app does not seem to respond to scrolling well on mobile/touch screen devices, the scrolling is rigid and only i can only swipe to the very botttom or very top by doing a fullscreen fling of the screen. Fix this problem. My globals.css: @tailwind base;
@tailwind components;
@tailwind utilities;
If the scrolling behavior on mobile devices in your React app is not smooth and feels rigid, there are a few possible reasons and potential fixes. Since this is a complex problem that could be caused by various factors, I'll provide a list of common issues and troubleshooting steps:
Overflows and Fixed Elements
Check that you haven't inadvertently set overflow properties on any containers that could interfere with scrolling behavior. Additionally, make sure fixed elements are not causing issues.
Disable Momentum Scrolling
Momentum scrolling can sometimes be disabled on iOS devices, leading to a rigid scrolling experience. You can enable momentum scrolling by using the -webkit-overflow-scrolling property in your CSS:
css
.page {
-webkit-overflow-scrolling: touch;
}
Verify Touch Event Handlers
If you have custom touch event handlers in your app (e.g., onTouchStart, onTouchMove, onTouchEnd), make sure they are not preventing the default browser scrolling behavior.
Check for Heavy JavaScript Execution
If there's heavy JavaScript running in the background or on scroll events, it could be causing performance issues. Make sure to optimize any such code, debounce or throttle scroll events, and remove any unnecessary JavaScript computations that could be affecting the scroll performance.
Review CSS Transforms
CSS transforms can sometimes interfere with hardware acceleration and smooth scrolling. Check any applied transformations and consider applying the will-change property to elements that will transform to hint to the browser they will change and should be optimized:
css
.translate-z-0 {
will-change: transform;
}
Examine Third-Party Libraries
Review any third-party libraries, such as Swiper, that handle scrolling or gestures to ensure they are correctly configured and not contributing to the issue. Verify their settings for mobile devices and look for properties related to smooth scrolling.
Preload Fonts
Ensure that fonts are being preloaded if they’re causing layout shifts. You mentioned a custom font in your globals.css, so make sure it loads efficiently.
Simplify Styles
Check if any complex styles, especially those related to layout and painting (e.g., shadows, gradients, fixed backgrounds), are causing repaint issues during scroll. Simplify styles where possible.
Test on Different Devices
Test the scrolling issue across different devices and browsers to determine if it's a problem with a specific device, browser version, or viewport size.
User
could using overflow-hidden in a page's component cause the error in the overall app
Assistant
Yes, using overflow-hidden on a page's component could potentially cause scrolling issues depending on the context in which it's used. overflow-hidden is a CSS property that prevents content from overflowing its container. When applied, the content that extends beyond the boundaries of the container will be clipped, and no scrolling mechanism will be provided to view the clipped content.
Here's how using overflow-hidden can cause scrolling issues:
Applied to the body or html elements: If overflow-hidden is applied to the body or html tags, it can prevent the entire page from scrolling.
Applied to a parent container: If overflow-hidden is applied to a parent container that encompasses large sections of the page or the entire page content, it can prevent scrolling within that container.
Nested containers: Sometimes, overflow-hidden is applied to nested containers within a page layout, which can cause unexpected scrolling behavior where certain areas of the page are not scrollable or only parts of the content can be scrolled.
Responsive design breakpoints: In responsive design, overflow-hidden might be applied only at certain breakpoints, leading to scrolling being disabled only on specific devices or viewport sizes.
In the CSS you provided, you have classes like .page that use overflow-y-auto and overflow-x-hidden, which seem to control scrolling behavior:
If any of these classes or similar ones are applied in a manner that impacts the scrollable content area on mobile devices, it could be causing the rigid or unresponsive scrolling you're experiencing. Also, applying overflow-hidden at breakpoints using media queries could turn off scrolling for certain screen sizes.
To debug this issue, you can try the following steps:
Temporarily remove or comment out overflow-hidden from your CSS and observe whether the scroll behavior changes on the mobile/touchscreen devices.
Verify if there are any containers with overflow-hidden that might be incorrectly encapsulating scrolling content.
useEffect(() => {
// Function to update the dimensions state based on the window size
const handleResize = () => {
if (window.matchMedia("(min-width: 960px)").matches) {
// If the screen width is larger than or equal to ‘lg’ breakpoint, set to desktop size
setDimensions({ width: 1000, height: 1000 });
} else {
// If smaller, set to mobile size
setDimensions({ width: 450, height: 450 });
}
};
// Set the initial globe size on component mount
handleResize();
// Add event listener for window resize
window.addEventListener('resize', handleResize);
// Remove event listener on cleanup
return () => window.removeEventListener('resize', handleResize);
}, []);
useEffect(() => {
// Check if the globe instance is loaded
if (globeRef && globeRef.current) {
const kenyaCoordinates = {
lat: 2.286389, // latitude for Nairobi, Kenya
lng: 18.82023 // longitude for Nairobi, Kenya
};
globeRef.current.pointOfView(kenyaCoordinates, 3000); // Animate the camera movement over 3000ms (3 seconds)
}
}, []);
useEffect(() => {
const handleRouteChange = () => {
// You could update state here to ensure fresh data is fetched when a route changes
setArcsData(travelHistory.flights);
};
router.events.on('routeChangeComplete', handleRouteChange);
// Fetch the initial data
setArcsData(travelHistory.flights);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events]);
return (
<Globe
ref={globeRef}
hexPolygonsData = { countries.features }
hexPolygonResolution = { 3}
hexPolygonMargin = {0.75}
hexPolygonAltitude = {0.01}
hexPolygonUseDots = {false}
enablePointerInteraction ={false}
onGlobeReady={() => setGlobeReady(true)}
showAtmosphere = { true}
atmosphereColor="#ffffff"
atmosphereAltitude = { 0.12}
backgroundColor="rgba(0, 0, 0, 0)"
globeImageUrl="//unpkg.com/three-globe/example/img/earth-dark.jpg"
hexPolygonColor = {(e) => {
return ["KEN", "CHN", "FRA", "ZAF", "JPN", "USA", "AUS", "CAN"].includes(e.properties.ISO_A3)
? "#9cff00"
: "rgba(255, 255, 255, 0.5)";
}}
width={dimensions.width}
height={dimensions.height}
arcsData={arcsData}
arcColor = {(e) => {
return e.status ? "#9cff00" : "#f13024";
}}
arcAltitude = {(e) => {
return e.arcAlt;
}}
arcStroke = {(e) => {
return e.status ? 0.5 : 0.3;
}}
arcDashLength = { 0.9}
arcDashGap = { 4}
arcDashAnimateTime = { 1000}
arcsTransitionDuration = { 1000}
arcDashInitialGap = {(e) => e.order * 1}
labelsData = { airportHistory.airports }
labelColor={() => "#ffffff"}
labelDotOrientation = {(e) => {
return e.text === "NGA" ? "top" : "right";
}}
labelDotRadius = { 0.35}
labelSize = {1.1}
labelText = {"city" }
labelResolution = { 6}
labelAltitude = { 0.07}
pointsData = { airportHistory.airports }
pointColor={() => "#ffffff"}
pointsMerge = { true}
pointAltitude = { 0.07}
pointRadius = { 0.10}
/>
);
The transitionDelay computation in the Transition component doesn't need to re-check the globeReady condition since the if block only runs when globeReady is false. The logic can be simplified.
This retains the current logic but is more concise.
To fix the potential issues, you need to:
Ensure that setGlobeReady(true) is called at the appropriate time when the globe is truly ready.
Revisit the dependencies of useEffect in GlobeComponent for setting the initial POV to make sure it's responsive to the relevant state changes.
Simplify the transitionDelay logic and ensure it's robust against all possible states.
As long as the context is shared correctly and both components work with the same sources of truth (globeReady in this case), there should be no contradiction in behavior.
// In GlobeComponent
// Define a state to track if there's an error loading the globe
const [globeError, setGlobeError] = useState(false);
// ...
// Then in the Globe component's onError or similar lifecycle/error handling
onGlobeError={() => {
console.log('Globe failed to load');
setGlobeError(true);
setGlobeReady(false); // optional, depending on how you want to handle errors
}}
// And then use the globeError state in your Transition component to conditionally activate the fallback rendering or error UI
This allows you to signal to users that something has gone wrong without leaving them in an indefinite loading state.
4. Ensuring Globe Loads Correctly
Make sure that the Globe component from react-globe.gl has all required props correctly set and that the resources it depends on (e.g., globeImageUrl) are available and not blocked by CORS policies or other network issues.
Finally, depending on the root cause which you might find after debugging, you might reach out to the maintainers of react-globe.gl if there's an issue with the library itself, or you may need to adjust the implementation based on any findings and recommendations for the component's usage.
The refactor should ensure the transition relies directly on the state that indicates readiness (isLoaded), instead of indirectly through a separate variable (transitionDelay). This way, you're tying the animation logic closer to the actual state intended to control it.
.hamburger-btn {
display: none; /* Hide on larger screens /
position: fixed; / Fixed at the top or as per your design /
top: 1rem;
right: 1rem;
background: transparent;
border: none;
z-index: 51; / Higher than the nav's z-index to be clickable */
}
/* This media query will apply styles for screens smaller than 1024px /
@media (max-width: 1024px) {
.hamburger-btn {
display: block; / Show the button */
}
As a last resort, create a minimal test case with a simple setup and slowly reintroduce elements and styles while testing on a mobile device until you find the cause of the scroll issues.
Here's a quick checklist of what to do:
Check all overflow properties in your CSS.
Ensure -webkit-overflow-scrolling: touch; is set for smooth scrolling on iOS.
Optimize heavy JavaScript, especially in scroll handlers.
Apply will-change: transform; to optimize CSS transformations.
Confirm correct configuration of third-party libraries handling scrolling/gestures.
Test across multiple devices and create minimal test cases to isolate the issue.
After making these changes, be sure to comprehensively test your app's scrolling behavior on actual mobile devices. If the issue persists, consider using browser dev tools to profile the performance during scroll and identify any bottlenecks.
Inspect the page using mobile device emulation in developer tools to see how overflow properties are affecting the page layout at different viewport sizes.
Check for other CSS properties that may affect scrolling, such as position: fixed; or height: 100vh;, which can sometimes interfere with scroll behavior on mobile devices.
By carefully analyzing and testing the layout, you should be able to diagnose and resolve the scrolling issues you're encountering on mobile/touchscreen devices.