A step-by-step guide on declaring a function in Next JS

I am working on a NextJS project and need to define a function that can be invoked by native code (Android/iOS) and call another function which in turn triggers the native code.

My goal is to make these functions accessible throughout the entire project so they can be called whenever needed without any issues.

I currently have a snippet of working code:

<html>
<head></head>
<body>

<script>
    var counter = 1;
    function buttonClicked(e) {     
        invokeCSharpAction(counter++);
    }

    function nativeDemand(data) {
         var el = document.getElementById('webtext');
         el.innerHTML = data;
        return 'test'
    }

</script>

<button onclick='javascript:buttonClicked(event)'>Click Me!</button>
<div id='webtext' style='font-family: script'><b>This web text will change when you push the native button.</b></div>
</div>
</html>
"

However, I am facing difficulties integrating these functions into my next project. When I add them to a page, they are not recognized as app functions. Additionally, since the invokeCSharpAction function is not defined anywhere (since it is picked up by the native app), the build process fails.

I attempted to create a script item in the public/static/ folder with these functions and include them on the page using

<script type="text/javascript" src="/static/script.js" async>
, but this approach did not work as expected.

As a newcomer to NextJs, any advice or guidance would be greatly appreciated.

Answer №1

To insert a script tag inside the body tag, just fill in the innerHTML as shown below:

<script type="text/javascript" dangerouslySetInnerHTML={{ __html: "function buttonClicked(e) { invokeCSharpAction(counter++); }"}}>
            </script>

You are free to include any javascript code within the __html attribute, it will be excluded during the build process and treated as standard JS in your future app.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What type of code is typically found within a class that has been declared under the ngModule decorator?

As a beginner in the world of Angular, I have noticed various examples that utilize ngModule decorators above an empty class. My question is: Is the class placed right after the ngModule decorator solely for initializing a module, or does it have addition ...

The art of effectively overloading functions within TypeScript interfaces

I have the following interface definition: interface foo1 { add(num1: number, num2: number): number; subtract(num1: number, num2: number): number; } Next, I instantiate an object in the shape of foo1: let myFoo1: foo1; myFoo1.add(5, 6); // OK m ...

What is the method to conceal the card icons displayed in the Stripe Payment Element?

Using Stripe Payment Element I am tasked with integrating Stripe payment for a client, but they specifically do not want the card icons (MasterCard, Visa, etc.) to be displayed. After attempting to hide them using Elements Appearance API without success, ...

What is the best way to determine in component.html whether the column type is equal to 1 to show the label text "Active,"

Having trouble checking the value of an object named ReportControl. If the column type is 1, display the label "active"; otherwise, display the label "not active" on reportcomponent.html. The data for the ReportControl object is as follows: {"reportId": ...

The 'MY_EVENTS_LOAD' argument is incompatible with the 'TakeableChannel<unknown>' parameter in the yeild takeLatest function

I am encountering a TypeScript error while using Redux and Saga as middleware. The error message is as follows: No overload matches this call. The last overload gave the following error. Argument of type '"MY_EVENTS_LOAD"' is not assignabl ...

Implementing a preview feature for markdown and LaTeX code in a ReactJS application

Recently, I launched a full-stack blogging website here. While using the react-quill library for writing blogs due to its extensible architecture and expressive API, I realize that I now need something that can handle both markdown and LaTeX. Is there a li ...

Utilizing getStaticProps to fetch dynamic product data in Next.js

Hey! I'm encountering an issue with implementing getStaticProps for a dynamic product component. It seems that I can't use the query param in the getStaticProps function, and so my code is failing to run as expected. Any help would be greatly app ...

Automatically determine prop type from configuration settings

Can the correct prop type be dynamically inferred based on the component type provided in the same prop? I currently have a component that correctly infers the expected props based on the specified component type. export interface IFieldTypeProps<TComp ...

How can I find the name of a function in TypeScript?

Does anyone know how to retrieve the name of a function passed in as a parameter? console.clear(); class A{ test(){ } testCall(fnc:Function){ console.log(fnc.name); // I want it to display 'test' here, not empty console.log( ...

obtain a list of elements using ViewChild attribute

In Angular 8, I have created a generic form with a form array. I am trying to retrieve all elements that contain the ViewChild id. However, when I try to output the ViewChild element using console.log, it only displays one element instead of a list. How ...

Getting the item that was clicked on a Chart in a PrimeNG chart within an Angular application can be achieved by following these

I am trying to implement a bubble chart and I would like the function to be called when a user clicks on one of the bubbles. What is the best way for me to pass the data to this function? https://i.stack.imgur.com/FYiSP.png <p-chart type="bubble" [da ...

Adding and removing/hiding tab-panels in Angular 4 with PrimeNg: A step-by-step guide

I'm currently working on a tabView project with a list of tab-panels. However, I am struggling to find a way to dynamically hide and unhide one of the tab panels based on specific runtime conditions. Does anyone have any suggestions or insights on how ...

Jest | Testing Tool for Functions with Multiple Parameters

I have developed a new tool that requires 3 parameters: value (string), service (any - an actual GET service), and name (string). Below is the code for the tool: import { serverErrorResponseUtil } from 'util/serverErrorResponseUtil'; import { H ...

Issue TS2365: The operation of addition cannot be performed between an array of numbers and the value -1000

I'm encountering an error in my ng serve logs despite the function functioning properly with no issues. However, I am concerned as this may pose a problem when building for production. How can I resolve this error? uuidv4() { return ([1e7]+-1e3+- ...

Steer clear of using the "void" return type and instead utilize an enum subset for better clarity

I am exploring the creation of a type-safe API-SDK where each entity supports different API endpoints based on an enum. In this scenario, only two out of three entities allow posting. Although calling the post-function with a known type resolves correctl ...

Struggling with configuring internationalization in NestJS

Currently, I am working on a NestJS project where my lead assigned me the task of returning different errors to the frontend based on the language in the request header. After some research, I decided to use i18n for this purpose. However, when testing it ...

Automatically retrieve the PDF file by obtaining the file path string from an API request

Is it possible to automatically download a PDF in the browser instead of just returning a file path string? Here's the code snippet I have: getMergedPDF(filesToUpload: Array<string>) { return this.http.post<string>('http://localh ...

Is there a possibility of a @types/jest version 27 coming out soon?

It appears that all Jest related packages I've come across are currently on version 27, except for this one. I wonder if there's a specific reason for this disparity. The Jest documentation mentions the importance of matching versions with associ ...

Why does my array seem to update only once in the view?

I am currently working on a project that aims to visually represent sorting algorithms, but I have encountered an issue. In order to effectively visualize the sorting process of an algorithm, it is crucial to display every change in the array as the proc ...

Error: The Select2 query service is not available

I am looking to enhance the search functionality for my select2 dropdown. My goal is to trigger a service call with the search parameters once 3 characters are typed into the search field. However, when I try to select an option from the dropdown, I encou ...