Nesting components to build scenes

Back to Modules

Nesting Components to Build Scenes in React Three Fiber

In React Three Fiber (R3F), building complex 3D scenes is made intuitive by leveraging React's component-based architecture. This means you can nest R3F components just like you would nest regular React components, creating a hierarchical structure that mirrors the Three.js scene graph.

How Nesting Works in R3F

Example: Nested Boxes

This example demonstrates how to nest components to create a group of boxes that can be transformed as a single unit. Note that this requires a React environment to run.

import React from 'react';
import { Canvas } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';

// A reusable component for a colored box
function Box({ position, color }) {
  return (
    <mesh position={position}>
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color={color} />
    </mesh>
  );
}

// A component that groups multiple boxes
function BoxGroup() {
  return (
    // The <group> component acts as a container for other Three.js objects.
    // Transformations applied to the group will affect all its children.
    <group position={[0, 0, 0]}>
      <Box position={[-1.5, 0, 0]} color="hotpink" />
      <Box position={[0, 0, 0]} color="orange" />
      <Box position={[1.5, 0, 0]} color="lightblue" />
    </group>
  );
}

// The main scene component
export default function Scene() {
  return (
    <Canvas>
      <ambientLight intensity={0.5} />
      <pointLight position={[10, 10, 10]} />

      {/* Nesting the BoxGroup component */}
      <BoxGroup />

      {/* Another group, demonstrating independent positioning */}
      <group position={[0, 2, 0]}>
        <Box position={[-0.75, 0, 0]} color="green" />
        <Box position={[0.75, 0, 0]} color="purple" />
      </group>

      <OrbitControls />
    </Canvas>
  );
}