Search code examples
javascriptreactjsmagenta

translating vanilla JavaScript to React component


im trying to understand how we can translate a very simple javascript program into ReactJS. My limited front end experience is with React, where things are wrapped in components or functions to render output.

This simple program has 3 components, which i would like to place into a React class or function:

1, a JavaScript object for note pitches.

TWINKLE_TWINKLE = {
  notes: [
    {pitch: 60, startTime: 0.0, endTime: 0.5},
    {pitch: 60, startTime: 0.5, endTime: 1.0},
    ... 
  ],
  totalTime: 5
};

2, the import, which can output notes:

player = new mm.Player();

3, the runner, which should output them.

player.start(TWINKLE_TWINKLE);
player.stop();

I would like to wrap this in a react class that i could then export. I know this may be a very simple question, but it would be very helpful to understand.


Solution

  • First, instal the proper dependency:

    npm install @magenta/music
    

    Then, inside your React code, do the following:

    import React from "react";
    import * as mm from "@magenta/music/es6";
    
    class App extends React.Component {
      constructor(props) {
        super(props);
    
        this.TWINKLE_TWINKLE = {
          notes: [
            { pitch: 60, startTime: 0.0, endTime: 0.5 },
            { pitch: 60, startTime: 0.5, endTime: 1.0 },
            { pitch: 67, startTime: 1.0, endTime: 1.5 },
            { pitch: 67, startTime: 1.5, endTime: 2.0 },
            { pitch: 69, startTime: 2.0, endTime: 2.5 },
            { pitch: 69, startTime: 2.5, endTime: 3.0 },
            { pitch: 67, startTime: 3.0, endTime: 4.0 },
            { pitch: 65, startTime: 4.0, endTime: 4.5 },
            { pitch: 65, startTime: 4.5, endTime: 5.0 },
            { pitch: 64, startTime: 5.0, endTime: 5.5 },
            { pitch: 64, startTime: 5.5, endTime: 6.0 },
            { pitch: 62, startTime: 6.0, endTime: 6.5 },
            { pitch: 62, startTime: 6.5, endTime: 7.0 },
            { pitch: 60, startTime: 7.0, endTime: 8.0 },
          ],
          totalTime: 8,
        };
        this.player = new mm.Player();
      }
    
      play = () => {
        if (this.player.isPlaying()) {
          return;
        }
        this.player.start(this.TWINKLE_TWINKLE);
      };
    
      render() {
        return (
          <div>
            <button type="button" onClick={this.play}>
              Play!
            </button>
          </div>
        );
      }
    }