Skip to content

Componentize

Video Lecture

Section Video Links
Componentize Componentize Componentize

Description

We will begin to componentize elements of our basic template so that we become more confident in restructuring our applications.

We can convert the Canvas and the mesh from our JSX into their own components.

We will convert the mesh into a component first.

Create a new file in the ./src folder named Box.jsx

We will create a function component in it named Box.

Note the capitalized B in Box. When we create our own components, we need to uppercase the first letter if we want to use them in our JSX. Lowercase tags within out JSX will be treated as existing HTML elements. Or in the case that the JSX, is a descendant of React Three Fiber, it will be treated as Three.JS object.

./src/Box.jsx

1
2
3
4
5
6
7
8
export default function Box() {
  return (
    <mesh>
      <boxGeometry />
      <meshBasicMaterial color={0x00ff00} wireframe />
    </mesh>
  )
}

Next we will convert the Canvas into its own component as well.

Create a new file in the ./src folder named App.jsx

./src/App.jsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import { Canvas } from '@react-three/fiber'
import Box from './Box'

export default function App() {
  return (
    <Canvas camera={{ position: [0, 0, 2] }}>
      <Box />
    </Canvas>
  )
}

We just created a function component named App, and are now referencing the Box function component.

And then finally update ./src/index.jsx code to be

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './styles.css'
import App from './App'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>
)

And now we are referencing the App function component.

Working Example

<>
Components and Props reactjs.org
Strict Mode reactjs.org

GitHub Branch

git clone https://github.com/Sean-Bradley/React-Three-Fiber-Boilerplate.git
cd React-Three-Fiber-Boilerplate
git checkout componentize
npm install
npm start

Comments