I want to declare a method in a JS file and use it in the .html.erb like this below method
const getSetHtml = () => {
console.log("Hello World");
}
and in the view .html.erb like this below code
onclick="getSetHtml()"
but it's showing
Uncaught ReferenceError: getSetHtml is not defined
I imported files like below
// /app/javascript/application.js
import "@hotwired/turbo-rails";
import "controllers";
import "trix";
import "@rails/actiontext";
import "trix";
import "@rails/actiontext";
import "./bootstrap.bundle.min";
import "./editor"; // this file
Note: Others JS library is working fine but the custom method isn't working.
Thanks
Why do you want to set the function with const? If it fits with your specific use case, cool! Otherwise I would personally just go ahead and define it regularly, either way here is the syntax for what you're trying to do.
const getSetHtml = function() {console.log("Hello World")};
Your current function returns the function itself rather than returning the return value of the function(the console.log("Hello World")).
I can't be entirely sure but I believe in your application.js you can just import the file like this I would try the other thing first: import "editor";
I hope this helps even a little, good luck. Let me know how it goes!
You can expose your function by adding it to the global object
global.getSetHtml = () => {
console.log("Hello World");
}