Design+Code logo

Quick links

Suggested search

During the first part, we will learn all the basics of using three.js. The second part is a bit more advanced, which is animation, while the last part is how to import your own 3D model.

It uses WebGL and JS to create a 3D environment. You can render 3D shapes in a scene. On your page, we are stacking elements one on top of another. A 3D object can be rendered using Three.js.

CodeSandbox link

You can find the initial code here and the final code here.

What is Three.js?

It uses WebGL and JS to create a 3D environment. You can render 3D shapes in a scene. On your page, we are stacking elements one on top of another. A 3D object can be rendered using Three.js.

Three.js in React part 1 image 1

Structure

This requires a few things.

  1. Canvas: 3D scene
  2. Geometry: Shape/object
  3. Material: Color/texture
  4. Lighting: Illuminates the scene

Dependencies

We need three important packages for this project.

  1. three: JavaScript 3D library

three, JavaScript 3D library

  1. @react-three/fiber: React renderer for three

React renderer for three

  1. @react-three/drei: Collection of helpers for three

Collection of helpers for three

If you use npm, you can use this command to install all of them.

npm i three @react-three/fiber @react-three/drei 

Canvas

You start by creating a React Three Fiber Scene with the Canvas object.

import { Canvas } from "@react-three/fiber";

<Canvas></Canvas>

Box

import React from "react";

export default function Box() {
  return (
    <mesh>
      <boxBufferGeometry attach="geometry" />
      <meshLambertMaterial attach="material" color="blue" />
    </mesh>
  );
}

Mesh

This class represents polygon mesh objects. It consist of a geometry and a material.

Geometry

This is the list of geometry. https://threejs.org/docs/?q=geometry#api/en/geometries/BoxGeometry

Material

This is the list of material. https://threejs.org/docs/?q=material#api/en/materials/Material

Resizing Canvas

We need to add a classname to the canvas so that we can add CSS through the wrapper. Set his height to 500px, make sure to refresh the page.

<Canvas className="canvas">
	<Box />
</Canvas>

const Wrapper = styled.div`
  canvas {
    height: 500px;
  }
`;

Resize geometry

When you hover over the box geometry's args property, you will see that it takes width, height, depth, and other parameters. Set the width, height and depth to 3.

<boxBufferGeometry attach="geometry" args={[3, 3, 3]} />

Rotation

By setting the rotation property, you can rotate the mesh.

<mesh rotation={[90, 0, 20]}>
	<boxBufferGeometry attach="geometry" args={[3, 3, 3]} />
  <meshLambertMaterial attach="material" color="blue" />
</mesh>

Lighting

We have no source of light, so the geometry is black.

<ambientLight intensity={0.5} />

<directionalLight position={[-2, 5, 2]} intensity={1} />

Interaction

Let's move on to the interaction, the drei collection has a function to rotate the geometry similarly to the github one.

import { OrbitControls } from "@react-three/drei";

<OrbitControls enableZoom={false} />

Texture

Let's apply a texture to a geometry now that you know how to add color. The useLoader hook takes 2 arguments, a loader and an input.

import React from "react";
import { useLoader } from "@react-three/fiber";
import { TextureLoader } from "three/src/loaders/TextureLoader";
import texture from "../textures/map.jpg";

export default function Box() {
  const colorMap = useLoader(TextureLoader, texture);

  return (
    <mesh rotation={[90, 0, 20]}>
      <boxBufferGeometry attach="geometry" args={[3, 3, 3]} />
      <meshStandardMaterial map={colorMap} />
    </mesh>
  );
}

Suspense

The code will not work since it needs a fallback in case the content cannot be retrieved. In this case, we should use the Suspense fallback.

import { Suspense } from "react";

<Suspense fallback={null}>
	<Box />
</Suspense>

MeshNormalMaterial

A material which maps normal vectors into RGB colors.

<meshNormalMaterial attach="material" />

Learn with videos and source files. Available to Pro subscribers only.

Purchase includes access to 50+ courses, 320+ premium tutorials, 300+ hours of videos, source files and certificates.

BACK TO

useLocalStorage Hook

READ NEXT

Three.js in React Part 2

Templates and source code

Download source files

Download the videos and assets to refer and learn offline without interuption.

check

Design template

check

Source code for all sections

check

Video files, ePub and subtitles

Videos

ePub

Assets

Subtitles

1

Intro to React Hooks

An overview of React Hooks and the frameworks you can use to build your React application blazingly fast

3:39

2

Create your first React app

Create your first React project from the Terminal and save it on your local computer

4:23

3

React Component

Create your first JSX component using React

2:54

4

Styling in React

How to style your React components using inline styling, separate stylesheets or styled-components

5:06

5

Styles and Props

Render different styles depending on different properties passed to your component

2:22

6

Understanding Hooks

Learn about the basics of React Hooks, which introduced at React Conf 2018

3:21

7

useState Hook

Use the useState hook to manage local state in your React component

2:54

8

useEffect Hook

Manage with your component's lifecycle with the useEffect hook

3:41

9

useRef Hook

Learn about the useRef hook, which replaces the JavaScript getElementById way

3:00

10

Props

Learn about props in React to pass data from parent to child components

3:11

11

Conditional Rendering

Render different UIs depending on different conditions and states

4:21

12

Load Local Data

Load local JSON data into your React application

4:04

13

Fetch Data from an API

Learn the basics of asynchronous functions and promises by fetching data from an API using fetch, useEffect and useState

5:40

14

Toggle a state

Learn how to toggle a state from true to false and back again

4:05

15

useInput Hook

Create a hook to get the value and the onChange event of input fields

6:04

16

Gatsby and React

Create a static content-oriented website using React on Gatsby

6:44

17

NextJS and React

Create your first NextJS React application

5:24

18

React TypeScript Part 1

Learn how to create a React TypeScript application using the Create React App, Gatsby and NextJS methods

8:19

19

React TypeScript Part 2

Learn the basics of TypeScript and how to use TypeScript in a React component

7:35

20

useScrollPosition Hook

Create a custom hook to listen to the current window position of the user

4:26

21

useOnScreen hook

Create a custom hook to listen to when an element is visible on screen

8:08

22

useContext Hook

Manage global states throughout the entire application

8:32

23

Fragments

Group multiple children together with React Fragments

2:43

24

Lazy Loading

Lazy Load heavy components to improve performance

4:05

25

React Suspense

Wait for data with React Suspense and React.lazy

3:13

26

Environment Variables

Make environment variables secret with a .env file

4:43

27

Reach Router

Create a multiple-pages React application with Reach Router

5:31

28

URL Params

Create unique URL with URL Params

4:04

29

SEO and Metadata

Optimize a React application for search engines with React Helmet

6:47

30

Favicon

Add an icon to a React website

3:03

31

Dynamic Favicon

Change the favicon's fill color depending on the user's system appearance

2:14

32

PropTypes

Implement props type-checking with PropTypes

3:54

33

Custom PropTypes

Create a custom PropType using a validator function

3:58

34

useMemo Hook

Prevent unnecessary re-renders when the component stays the same

4:05

35

forwardRef Hook

Forward a ref to a child component

3:28

36

Handling Events

How to handle events in React

5:44

37

Spread attributes

Learn how to make use of the spread operator

3:35

38

useMousePosition Hook

Detect the user's mouse position on a bound element

4:55

39

useReducer with useContext Part 1

Create a reducer to be used in a context

7:33

40

useReducer with useContext Part 2

Incorporate useReducer with useContext

6:48

41

useReducer with useContext Part 3

Connect the context and reducer with the frontend

5:43

42

Netlify

Deploy to production using Netlify

5:08

43

Gatsby Cloud

Deploy to production using Gatsby Cloud

6:19

44

Gatsby Plugin Image

Use gatsby-plugin-image for automatic image resizing, formatting, and higher performance

8:11

45

useOnClickOutside Hook

Toggle a modal visibility with a useOnClickOutside hook

6:32

46

useWindowSize Hook

Create a hook to determine the width and height of the window

4:14

47

usePageBottom hook

Detect if the user scrolled to the bottom of the page

4:48

48

useLocalStorage Hook

Store an item in a browser's local storage

5:27

49

Three.js in React Part 1

Bring your website to life with beautiful 3D objects

17:33

50

Three.js in React Part 2

Bring your website to life with beautiful 3D objects

11:18

Meet the instructor

We all try to be consistent with our way of teaching step-by-step, providing source files and prioritizing design in our courses.

Willie Yam

Front-end/UI developer at Design+Code

I do UI coding. HTML/CSS/JS/SWIFTUI dev.

icon

10 courses - 37 hours

course logo

Design and Prototype an App with Play

Build a completely functional prototype without writing a single line of code from your phone

3 hrs

course logo

Create a 3D site with game controls in Spline

Build an interactive 3D scene implemented on a ReactJS site using Figma and Spline

2 hrs

course logo

Build a Movie Booking App in SwiftUI

Learn how to create an iOS app based on a beautiful UI design from Figma with interesting animations and interactions, create a custom tab bar and use navigation views to build a whole flow

1 hrs

course logo

Build Quick Apps with SwiftUI

Apply your Swift and SwiftUI knowledge by building real, quick and various applications from scratch

11 hrs

course logo

CSS Handbook

A comprehensive series of tutorials that encompass styled-components, CSS, and all layout and UI developments

1 hrs

course logo

Advanced React Hooks

Learn how to build a website with Typescript, Hooks, Contentful and Gatsby Cloud

5 hrs

course logo

Unity for Designers

If you want to make a game and don't know where to start, you are in the right place. I will teach you how to use Unity, code in C# and share essential tips and tricks to make your first game.

5 hrs

course logo

Create a Javascript Game

Learn how to create a web game using Phaser 3, a popular javascript game engine. Draw a map using an editor, implement the player, make the player move, apply physics, collisions, and implement the enemies.

2 hrs

course logo

Build an ARKit 2 App

Introduction to ARKit and learn how to make your own playground. You will be able to add models or even your own designs into the app and play with them

4 hrs

course logo

Create a SpriteKit Game

Overview of SpriteKit a powerful 2D sprite-based framework for games development from Apple and learn how to create your very own platform

3 hrs