Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i divide code into separate files?

I'm building on my Three.js project and have been struggling for some time on how i could divide two functions into separate files

I have my Main.js(React Class Component) file that contains 200> rows of code and two of these functions that i would like to separate are:

startAnimationLoop()

  startAnimationLoop = () => {
    const tableBoard = this.scene.getObjectByName('tableSurface');
    tableBoard.rotation.y += this.title.RotationSpeed;

    this.renderer.render(this.scene, this.camera);
    this.requestID = window.requestAnimationFrame(this.startAnimationLoop);
  };

userGUI() ('dat.gui' Controller)

  userGUI = () => {
    const getTableSurface = this.scene.getObjectByName('tableSurface');

    this.gui = new dat.GUI();
    const controls = function() {
    this.RotationSpeed = 0.00;
  }
    this.title = new controls();
    this.gui.add(this.title, 'RotationSpeed', 0.0, 0.025);
  }

I call these functions inside the componentDidMount()

componentDidMount() {
    this.sceneSetup();
    addLights({ scene: this.scene });
    addFloor({ scene: this.scene })
    this.userGUI();
    this.startAnimationLoop();
    window.addEventListener("resize", this.handleWindowResize);
  }

I've been struggling with it for quite some time and any suggestions on how i could proceed with this process would be much appreciated.

like image 996
Arasto Avatar asked Feb 28 '26 16:02

Arasto


1 Answers

Personally I would not break it out, but if you want too, you need to export and import the methods. You also need to make sure you are calling it with the proper scope of this.

So make the file export the function

export const startAnimationLoop = () => {
  /* The Code
}

And your react component

import { startAnimationLoop } from './path/startAnimationLoop'

and when you call it

startAnimationLoop.call(this)

Or you can set it up in constructor with bind, and inside componentDidMount, you would use this.startAnimationLoop()

constructor(props) {
  super(props);
  this.startAnimationLoop = startAnimationLoop.bind(this);
}
like image 146
epascarello Avatar answered Mar 02 '26 04:03

epascarello