3D Portfolio
Responsive
Maybe you feared this moment but it's time to make our website responsive!
Now we need to recreate everything we did for the desktop version but for mobile!
Just kidding π€, we will use some techniques to make our 3D scene looks good on mobile.
I'd like to highlight that there is not one perfect solution to make a 3D scene responsive. It depends on many factors :
- The complexity of the scene
- The number of elements
- Performances
- What you want to achieve
For the CSS part, we will easily make our website responsive with media queries.
useMobile
We will use two techniques to make our 3D scene responsive:
- Changing the base position and scale of items based on the available width at our disposal. After a certain threshold, we will switch to a mobile version.
- Fine tuning the position and scale of items based on a
scaleFactor
. Our scene looks perfect on a1980px
screen but what about a1600px
screen? We will use ascaleFactor
to adjust the position and scale of items to keep the same look and feel.
Let's create a useMobile
hook in a src/hooks
folder to handle both techniques:
import { useState } from "react"; const REFERENCE_WIDTH = 1920; const MOBILE_THRESHOLD = 990; export const useMobile = () => { const [scaleFactor, setScaleFactor] = useState( window.innerWidth / REFERENCE_WIDTH ); const [isMobile, setIsMobile] = useState( window.innerWidth <= MOBILE_THRESHOLD ); return { scaleFactor, isMobile, }; };
We are using the useState
hook to store the scaleFactor
and isMobile
values. This will force a re-render when the values change.
We use two constants to define the perfect width we used to position our items and the mobile threshold (when we switch to the mobile version).
I chose not to use the config
for those variables
to make this hook reusable in other projects.
React Three Fiber: The Ultimate Guide to 3D Web Development
β¨ You have reached the end of the preview β¨
Go to the next level with Three.js and React Three Fiber!
Get full access to this lesson and the complete course when you enroll:
- π Full lesson videos with no limits
- π» Access to the final source code
- π Course progress tracking & completion
- π¬ Invite to our private Discord community
One-time payment. Lifetime updates included.