React-three-fiber render meshes conditionally


I’m trying to find a way to render a mesh conditionally.
Let’s say at the start of the client I want a single mesh to be generated. After some time, once some conditions are reached, I want to be able to generate other meshes at that time.
I know that we can call functions inside the “Html” part and make if-conditions. But it doesn’t want to rerender once the if conditions are changed.

It’s called JSX :blush:

As for the problem of re-rendering meshes itself - it’s not really possible to help without seeing the code :sweat_smile:

I’m not able to share it now sadly. But maybe if someone knows a code doing something similar to what I described, it might help.

For conditionally rendering components, one solution is useState.

const Meshes = () => {
    const [value, setValue] = useState("A");

    // Next you need some way to change the value, here I've just added an eventlistener 
    // that will toggle between A and B when you click
    useEffect(() => {
       window.addEventListener("click", () => {
           setValue(state => state === "A" ? "B" : "A")
    }, []);

   // Now if the value is A, render component A, otherwise, render component B
   return value === "A" ? <MeshComponentA /> : <MeshComponentB />;

Note, there’s nothing related to three.js here (although for actually rendering meshes in this simple style I’d recommend using React-three-fiber). It’s all standard React stuff so if anything is not clear you can refer to the official React tutorials.

1 Like