Search code examples
reactjspaperjs

Stuck porting paperjs to react/nodejs


I'm trying to port some paperjs code into a new react application. But I ran into some limitations.

In HTML: Currently I have 2 animation files in paperjs and for each one I have an HTML file which works with

In React : The following works

 componentDidMount() {
    var canvas = document.getElementById("myCanvas");
    paper.setup(canvas);

   require('./Lesson_1.js');

  paper.view.draw();
}

In React : The problem

I need to dynamically change the argument into require() based on the user choice, ...BUT

const lesson = './Lesson_1.js';
require(lesson) 

does not work as the require() function needs a literal !!

Question 1: Is there a workaround for this so I could require a lesson of my choice, since I may have many more lessons? React seems to ignore the script tags

Question 2: Since this component does not mount again when the user chooses another lesson, how do I clear the same canvas and reload a fresh lesson js file?

I have no problem, the way it works currently but porting to react is a problem. Someone suggested to be to keep running the old way and create an iframe in react to show the contents, but I was looking for a cleaner solution in react without dependencies to other programs.

Thanks for your help.


Solution

  • One possible workaround mentioned in this discussion is to use a switch statement.
    Here is a stackblitz demonstrating the solution.

    class App extends Component {
    
      componentDidMount() {
        paper.setup('canvas');
    
        const scriptToLoad = 'a';
    
        switch (scriptToLoad) {
          case 'a':
            require('./a.js');
            break;
          case 'b':
            require('./b.js');
            break;
        }
      }
    
      render() {
        return (
          <div>
            <canvas id="canvas"></canvas>
          </div>
        );
      }
    }