Adding OrbitControls in React using reactthree-fiber

React JSJavascript LibraryFront End Technology

In this article, we will see how to add OrbitControls in React using react-three-fiber. It is like making a camera; we can move on screen and view each side of any 3D object. We can use OrbitControl to provide zoom and sliding effects too. So, let's get started.


Install the react-three/fiber library −

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

threejs and react-three/fiber will be used to add webGL renderer to the website. three-fiber will be used to connect threejs and react.

First create an orbital control object in App.js

import React, { useEffect } from "react";
import { Canvas, useThree } from "@react-three/fiber";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import * as THREE from "three";
import "./App.scss";

const CameraController = () => {
   const { camera, gl } = useThree();
      () => {
         const controls = new OrbitControls(camera, gl.domElement);
         controls.minDistance = 3;
         controls.maxDistance = 20;
         return () => {
      [camera, gl]
   return null;
  • CameraController is used to add orbital control on the whole screen.

  • useThree() gives you a camera object, which is used to move on screen.

  • gl indicates the area on which you are moving.

  • In useEffect, we combined both the OrbitControls object.

  • Then we added the minDistance and maxDistance parameters to restrict the movement on screen.

Next, add the following lines in App.css

* {
   box-sizing: border-box;
   width: 100%;
   height: 100%;
   margin: 0;
   padding: 0;

   background: #f1f4f8;
   position: fixed;

This CSS is used to make the canvas match parent size.

Now, let's add OrbitControl in the App component. Add the following lines of code in App.js

export default function App(){
   return (
         <CameraController />
         <ambientLight />
         <spotLight intensity={0.3} position={[5, 10, 50]} />
            <boxGeometry attach="geometry" args={[3, 2, 1]} />
            <meshPhongMaterial attach="material" color="hotpink" />

We created a cuboid and added our previous orbitcontrol object “CameraController” in the App component. OrbitControl is used to add zoomIn, zoomOut, moving, and other effects on our canvas.


On execution, it will produce the following output −

Published on 28-Sep-2021 12:45:51