casper's Profile Image

Full Stack Web/Mobile Developer

Nov, 7, 2023

React Vite Js Tailwind Css And React Three Fiber Boilerplate

You can start with this boilerplate to make react three fiber app

React Vite Js Tailwind Css And React Three Fiber Boilerplate Image
yarn create vite

Enter a project name. Select React Select Javascript

Open your project on Visual Studio Code or any code ide you want.

Install Tailwind CSS dependencies and initialize.

yarn add -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Update "tailwind.config.js"

/** @type {import('tailwindcss').Config} */
export default {
  content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
};

Update "index.css"

@tailwind base;
@tailwind components;
@tailwind utilities;

You can delete "App.css" file if you won't use.

Update "App.jsx" file:

const App = () => {
  return (
   <div className="flex items-center justify-center min-h-screen">
      <h1 className="text-3xl text-blue-600">
        React Three Fiber with TailwindCSS
      </h1>
    </div>
  );
};
export default App;

Install React Three Fiber dependencies:

yarn add three @types/three @react-three/fiber

Create "components" folder in your "src" folder and create "Box.jsx" file:

import React, { useRef, useState } from "react";
import { useFrame } from "@react-three/fiber";

const Box = (props) => {
  // This reference will give us direct access to the mesh
  const meshRef = useRef();
  // Set up state for the hovered and active state
  const [hovered, setHover] = useState(false);
  const [active, setActive] = useState(false);
  // Subscribe this component to the render-loop, rotate the mesh every frame
  useFrame((state, delta) => (meshRef.current.rotation.x += delta));
  // Return view, these are regular three.js elements expressed in JSX
  return (
    <mesh
      {...props}
      ref={meshRef}
      scale={active ? 1.5 : 1}
      onClick={(event) => setActive(!active)}
      onPointerOver={(event) => setHover(true)}
      onPointerOut={(event) => setHover(false)}
    >
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color={hovered ? "hotpink" : "orange"} />
    </mesh>
  );
};

export default Box;

Update your "App.jsx" file:

import React from "react";
import { Canvas } from "@react-three/fiber";
import Box from "./components/Box";

const App = () => {
  return (
    <div className="w-[100vw] h-[100vh]">
      <Canvas>
        <ambientLight />
        <pointLight position={[10, 10, 10]} />
        <Box position={[-1.2, 0, 0]} />
        <Box position={[1.2, 0, 0]} />
      </Canvas>
    </div>
  );
};

export default App;

Your boilerplate is ready! you can interact with the box by clicking or hovering them.

0
0

Comments (0)