0

I am trying to develop a custom gutenberg block. I have a form in save.js:

export default function save() { return ( <div {...useBlockProps.save()}> <form onSubmit={handleSubmit}></form> </div>);} 

File view.js is defined in block.json ("viewScript": "file:./view.js",)

const handleSubmit = async (event) => { event.preventDefault(); const formData = new FormData(event.target); ... }; 

But when the block renders, it fails.

Uncaught ReferenceError: handleSubmit is not defined 

Its all nice if i use "traditional" javascript (e.g. jQuery, console.log), so enqueueing is not the problem. I am pretty new with "modern" javascript (React, Angular...) and the question is surely pretty dumb, but i am looking for a proper way to coding and not only looking for a functional solution.

1
  • Add export in view.js to export handleSubmit export const handleSubmit = async (event) => { then import handleSubmit in the beginning of save.js page import { handleSubmit } from './save';CommentedDec 14, 2023 at 23:09

1 Answer 1

1

To achieve your goal:

  • All of your React logic will need to be in your edit.js file and not your save.js file. The save.js file is only for viewing the final data on the WP Admin after you save a post or on the live post.

  • The view.js file can only contain Vanilla JavaScript (from the way you are using it). Then when you save your block, on the saved post WP Admin screen or the live post screen you the React JSX you added in your save.js file will be converted to HTML and your view.js file will need to be Vanilla JavaScript that interacts with this HTML.

Let em know if this makes sense.

2
  • Thank you! You said The view.js file can only contain Vanilla JavaScript (from the way you are using it). So you mean it is possible to have jsx in view.js? If yes, how? Because I'm using vanilla js and I'm worried about having some possible and unexpected XSS issues there.
    – kodfire
    CommentedFeb 16, 2024 at 15:16
  • 1
    @kodfire In a WordPress block, the view.js file can only have JavaScript with NO frameworks (that's what I mean when I refer to Vanilla JavaScript), so it can't have JSX. The JSX you are referring to is part of React (source: react.dev/learn/writing-markup-with-jsx) which can NOT be used in the view.js file.CommentedFeb 16, 2024 at 22:31

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.