3D Portfolio

Starter pack

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 a 1980px screen but what about a 1600px screen? We will use a scaleFactor 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.

Three.js logoReact logo

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
Unlock the Full Course – Just $85

One-time payment. Lifetime updates included.