How to include plain JavaScript in a React app? - javascript

I'm trying to create a React page which includes a p5 sketch, but doing so seems to require me to rewrite standard JavaScript I would normally run in a browser to make it work as a react component.
For example, I'd like to have React serve this code to the client:
function setup() {
createCanvas(600, 600);
}
function draw() {
background(0);
}
But I can't find a way to just have React give the client a JavaScript file. Instead I have to create a component like this:
export default function(p: p5) {
p.setup = function setup() {
p.createCanvas(600, 600);
};
p.draw = function draw() {
p.background(0);
};
}
This might seem trivial but if my team and I can include code that we've already written which works outside of react without having to rewrite everything would make things much easier.
One way to solve the problem is to just place the file in the public directory of React and just serve it statically along with index.html, but I'd prefer to only give the client the file when it needs it instead of just serving every file at once. If I could just have a component import the JavaScript file and send it like it can do with images, that would be exactly what I'm looking for.
Edit: Sorry, to clarify what I meant, Node is what's actually serving things, what I want is when React renders a page it will also run JavaScript code as if it were written in a <script> tag in the HTML page.

I've solved it. Essentially I put all of the code I want to run in a file like sketch.js but surround it in a function which is exported:
export default function Sketch() {
function setup() {
createCanvas(600, 600);
}
function draw() {
background(0);
}
}
Then in app.js you can do something like:
import Sketch from './sketch';
Sketch();
That will run all of the code in that function in the client's browser.

So just an option, we do this for optionally loading certain scripts on our app. In your component on the constructor (or maybe the willMount, play around with it) create a new script tag and append that script tag to the head of you app. This will cause the script to only be run when this component is rendered (Depending on where you called the function to add the script tag). You might also have to think about removing the script tag depending on what your doing, but you get the idea.
The function would look something like this:
addScriptTag = () => {
script = document.createElement('script');
script.src = [url/path of the javascript you want to server from your node server];
// Or just set the javascript on the script tag by adding innerText and type arts
document.head.appendChild(script)
}
then do something like:
constructor() {
this.addScriptTag();
}

Related

Why p5js skethch integrated with Vaadin won't start?

I'm trying to integrate a p5js with the Vaadin. The goal is to plug p5js library and my p5js Sketch as well into the Vaadin's view component. So I would be able to launch and render my a p5js Sketch on client side and refer to some logic on the server side.
As I am figuring out once p5js library loaded it would start automaticaly (The p5js library is a script file with a main function inside round brakets) and catch my "setup()" and "draw()" functions from sketch. And this is exactly how it works if I make an empty html page and plug scripts there with tags.
In Vaadin I used #JavaScript annotation for both scripts and start localhost but hothing happens. Sketch won't start. There is test "console.log()" inside "setup()" function it won't works off too.
Also somehow I can't reach the sketch's functions from browser's console (Neither just "setup()", nor "window.setup()", nor "p5.setup() fit) but with tiny code modification I can. If I place my sketch code inside "window.ns={// my code}" I can refer to it via "window.ns..." in the console. So I'm pretty sure sketches are loaded with page.
What am I missing?
Here is Vaadin's view class I've made (Java):
#Route(value = "/MyView")
#JavaScript("p5.js")
#JavaScript("sketch.js")
public class MyView extends VerticalLayout {
public MyView() {
}
}
Here is the Sketch's code (JavaScript):
function setup () {
console.log(`test message`);
createCanvas(400, 400);
}
function draw () {
background(220);
}
There is no any error message relevant to the issue. The console is silent.
Update:
Also it might be useful if someone experienced look at the high-levevel library code to figure out how it starts:
high-levevel library code
The content of the JavaScript is not automatically executed. You need to add JavaScript call in your view, something like.
#Route(value = "/MyView")
#JavaScript("./p5.js")
#JavaScript("./sketch.js")
public class MyView extends VerticalLayout {
public MyView() {
getElement().executeJs("setup();draw();");
}
}

vanilla js import and export in old project

I am trying to clean up the js in an old project, where I cannot add things like typescript etc.
So I am trying to split up the functionality into different files, and create some order from the chaos (I currently have multiple 10k lines js files).
For example I have an index.js which is for a specific page.
On that page I am trying to call a function via an onclick to call dmrLookupByType
import * as dmrService from "../../services/DMRService.js";
// function to be called from HTML
function dmrLookupByType(type){
console.log("called dmrLookupByType function");
dmrService.dmrLookUp(type);
}
In DMRService.js there is a single function (so far)
export function dmrLookUp(type)
{
console.log("reached dmrLookup in DMRService file");
console.log("received type: ", type);
}
The script it self is included on the page as this.
<script type="module" src='/javascripts/src/pages/applicationCreate/index.js'></script>
But i keep getting "Uncaught ReferenceError: dmrLookupByType is not defined"
I also tried wrapping dmrservice in a class to use, but that didn't really change anything either.
Any ideas what I'm doing wrong?

How to handle page level pure javascript in react

First time using react and am converting a poc. Have a bunch of pure javascript, mostly code for animations on a canvas (almost game level). Each page has too much code to load it all in the base html file.
I'm sure there is something I'm missing in my searches, but I'm not sure the correct way to handle including it with each individual page.
I tried just putting it inline like this, but it doesn't like some of the code, so I'm assuming it's not the best way.
componentDidMount() { <script>....</script> }
Found an example doing
componentDidMount() {
const script = document.createElement("script");
script.src = "file.js";
script.async = true;
document.body.appendChild(script);
No matter how I path it, it just loads up the index page. So unexpected error < because it starts with < html>
Not sure it matters, but my JS includes a number of functions, var declarations, addEventListener and an onload.
You are looking for import.
import scriptFromGame from './script.js'
const App = ()=> {
// code reuse from script.js
//let's assume points
const {points} = scriptFromGame;
return <div> {points} </div>
}

How do I add a personal script to an existing node.js library?

I have a local copy of the hls.js library and I need to include a personal script with custom functions in it.
How do I go about adding a new script to the library and how do I use the function written in the new script?
Let's say that I want to add a script called hello.js that contains a function that logs "Hello World".
When I call that function in my main.js I need it to execute.
Any ideas on how to do this?
Currently, I'm getting an error that the function is not defined.
I placed the hello.js script in the src folder of the library but this (as expected) doesn't seem to work.
It should be possible to add functions to the exported hls.js object.
Your custom-script.js:
var hls = require('hls.js')
hls.customFunc1 = function () {
}
hls.customFunc2 = function () {
}
on main.js:
require('custom-script')
// your code follows
Any other code would be able to use the custom functions by just require'ing hls.js.

Use Javascript to call method within a flash (.swf) file?

I have a flash file that contains a package "game" which has a class "Scores" and a method setValue(). I want to write some lines of Javascript that allow me to call that method. Someone directed me to this tutorial, but I am still a bit confused.
Javascript: alert("start"); var so; so = document.embeds[0];
so.addParam("allowScriptAccess","always"); import flash.external.ExternalInterface;
ExternalInterface.call("setValue[2600]");
displays an alert to tell me that it has indeed began to execute
saves the embedded flash file into a variable and sets access
imports that class
calls the method
I am not sure about how this class thing works? This is just the bits and pieces I was able to come up with from that site, but I don't really understand how it all works (but certainly hope to eventually). This is the site: http://bytes.com/topic/flash/answers/694359-how-do-i-access-flash-function-using-javascript. When I execute the code with the importation nothing happens, but the alert does come up when I don't have that statement?
If someone could elaborate on how I might call that method, I would be very thankful! :)
The code you have there is a mix of JavaScript and ActionScript.
In ActionScript, you need to register the setValue function for external use, so it can be called from JavaScript. Code for it could look something like this:
package game
{
import flash.display.Sprite;
import flash.external.ExternalInterface;
import flash.text.TextField;
public class Scores extends Sprite
{
public var txtScore:TextField; // A textfield in the sprite
public function Scores()
{
// Register the function for external use.
ExternalInterface.addCallback("setValue", setValue);
}
private function setValue(value:Number):void
{
txtScore.text = String(value);
}
}
}
And the JavaScript could look something like this:
var so = document.embeds[0];
so.setValue(2600);
Adobe has the documentation with a lengthy but useful example here. They show the ActionScript as well as the JavaScript, and how they can interact in both ways.

Categories