I am using React and React Three Fiber and I plan to have a side bar with 12 options, which are used to hide/show 12 meshes on R3F canvas. The logic is that if the user selects an option(mesh), the other 11 meshes will be hidden, and if the user clicks the same option again all the meshes will be shown. I tried to create a boolean state for each of the option and use Ternary Operators for conditional rendering. However, I found it tricky because there will be numerous lines of codes if I do so, and I cannot simply return null for other meshes because the convexRev will not have "geometry" property and will report errors. I wonder if there is a simple way to achieve it.
What I have right now:
In App.js
:
const [showOnlyOption1, setShowOnlyOption1] = React.useState(false)
// With another 11 states which will be passed to ConvexHull.js
In Convexhull.js
:
.....
return(
<>
{showOnlyOption1 ? (
<>
<mesh ref={convexRefOption1}>
<motion.meshBasicMaterial initial="hidden" animate="visible" variants={var1}/>
</mesh>
<mesh ref={convexRefOption2}>
<motion.meshBasicMaterial initial="visible" animate="hidden" variants={var2}/>
</mesh>
<mesh ref={convexRefOption3}>
<motion.meshBasicMaterial initial="visible" animate="hidden" variants={var2}/>
</mesh>
.....
<mesh ref={convexRefOption12}>
<motion.meshBasicMaterial initial="visible" animate="hidden" variants={var2}/>
</mesh>
</>
):(
<>
<mesh ref={convexRefOption1}>
<motion.meshBasicMaterial initial="hidden" animate="visible" variants={var1}/>
</mesh>
<mesh ref={convexRefOption2}>
<motion.meshBasicMaterial initial="hidden" animate="visible" variants={var1}/>
</mesh>
<mesh ref={convexRefOption3}>
<motion.meshBasicMaterial initial="hidden" animate="visible" variants={var1}/>
</mesh>
.....
<mesh ref={convexRefOption12}>
<motion.meshBasicMaterial initial="hidden" animate="visible" variants={var1}/>
</mesh>
</>
)}
</>
)
My code works fine for selecting the first option, but I want to know except for copy-pasting the same format 11 times is there a better way to do so? No matter if it's about creating the buttons' state, handling the mesh and animation in R3F, or other syntaxes... Thanks in advance!
You can use initial={optionToShow === 1 ? 'visible' : 'hidden'}
It would work even better with a loop
const [optionToShow, setOptionToShow] = React.useState(undefined)
return (
<>
<mesh ref={convexRefOption1}>
<motion.meshBasicMaterial initial={optionToShow === 1 ? 'visible' : 'hidden'} animate="visible" variants={var1}/>
</mesh>
<mesh ref={convexRefOption2}>
<motion.meshBasicMaterial initial={optionToShow === 2 ? 'visible' : 'hidden'} animate="hidden" variants={var2}/>
</mesh>
<mesh ref={convexRefOption3}>
<motion.meshBasicMaterial initial={optionToShow === 3 ? 'visible' : 'hidden'} animate="hidden" variants={var2}/>
</mesh>
.....
<mesh ref={convexRefOption12}>
<motion.meshBasicMaterial initial={optionToShow === 12 ? 'visible' : 'hidden'} animate="hidden" variants={var2}/>
</mesh>
</>
)