Tips for getting my scripts to function properly with my components in next.js?

I am facing an issue with my script while using React and Next.js in my pages/_app.js file. The code snippet is as follows:

import axios from "axios";
import { $ } from "jquery";
import App from "next/app";
import Router from "next/router";
import { destroyCookie, parseCookies } from "nookies";

import Layout from "../components/_App/Layout";
import "../public/css/boot.css";
import "../public/css/icons.css";
import "../public/css/themes/style.css";
import "../public/jquery";
import "../public/scripts";
import baseUrl from "../utils/baseUrl";

// Rest of the code here

The complete code can be found at: https://codesandbox.io/s/dawn-mountain-vme5e?file=/pages/_app.js

I am encountering a ReferenceError where $ is not defined when I import my script into the _app.js file. This issue is causing my jQuery functions to not work correctly in my components.

I have searched for solutions but couldn't find any helpful resources to resolve this problem. It is hindering the progress of several projects that I am working on.

If you have any insights or suggestions on how to fix this issue, I would greatly appreciate your help. Thank you.

Answer №1

For a deeper understanding of your issue, let's delve into some theory. Next.js utilizes server-side rendering and static generation, meaning that all code is first executed on the server. Keep in mind that jQuery is a client-side library, so it cannot run on the server side. To ensure proper execution, you must ensure that all jQuery code runs exclusively on the client side by checking for the existence of the window object before executing any jQuery functions. Additionally, make sure to include jQuery in your scripts.js file.

To update the scripts.js file:

import $ from "jquery";

if (typeof window !== "undefined") {
  $(function () {
    // Add your jQuery functions here...
  }
}

Next, modify the componentDidMount function in _app.js:

componentDidMount() {
  window.addEventListener("storage", this.syncLogout);
}

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

React does not allow objects as children (received: object containing keys {_id, date, createdAt, updatedAt, __v})

Encountering an error while attempting to render an object ({day} in the react Component below) retrieved from the database: Error: Objects cannot be rendered directly in React (found: object with keys {_id, date, createdAt, updatedAt, __v}). If you inte ...

``Is there a way to position an image at the center in Python dash?

Can someone help me with centering an image in my Flask dash app? Here is the code I have: import dash from dash import html, dcc import dash_bootstrap_components as dbc app = dash.Dash(__name__) app.layout = html.Div([ dbc.CardImg(src=r'assets/ ...

Activate the button to effortlessly load pages with a visually engaging animation

I have been facing a problem for the past couple of days. I need help with achieving a specific functionality on my website. When button1 is clicked, I want to load the page in a div class named "loadpage" with an animation coming from the left. Similarl ...

Infinite loop occurring when setting state to child component in React

On a page featuring dropdown menus for content searching, the dropdown is non-functional but provides context. This page serves as a listing page. After performing calculations on the listing page and updating the state, I encounter an infinite loop when ...

Exclude objects in array that do not match filter criteria

I am facing a challenge with filtering an array of objects. (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: {tbi_tblid: 512100013, long_name: "", short_name: "", short_name2: "", trickysort: "", …} 1: {tbi_tblid: 512100013, long_n ...

An error occurred when trying to set a cookie using Set-Cookie in a react application

Currently, I am immersed in a small project that involves user authentication via email and password before gaining access to their individual profiles. The backend operates on cookies which are established once the correct email and password combination i ...

Determining the position of p5.js input in relation to the canvas

Show me what you’ve got: function initialize() { var board = createCanvas(960,540); board.parent("drawingPad"); background('white'); var textbox = createInput(); textbox.position(10,10); textbox.parent("drawingPad"); } I’ve cre ...

Switching Bootstrap Navbar Active State with JavaScript

I have encountered an issue with using the "active" class on my navbar navigation items in Bootstrap 4. When I click on the links, the active state does not switch as intended. I have tried incorporating JavaScript solutions from similar questions but have ...

Is there a way to directly access the React component that was clicked?

I'm looking to dynamically change the class of a component when clicked. By using state to create a new component with properties such as name and done (initiated as false), which are then added to the todos array, I want to find out how to identify t ...

Resolving the issue: "How to fix the error "Credentials are not supported if the CORS header 'Access-Control-Allow-Origin' is '*' in React?"

Recently, I encountered some CORS issues while using a third party API in my front-end application. After reaching out to the API maintainers, they lifted the CORS control by adding a * to Access-Control-Allow-Origin, which seemed like the perfect solution ...

TextInput in React Native form not registering any user input

I'm facing an issue with typing in the TextInput component. The letter gets typed and then instantly deleted, indicating a problem with state updating. Can anyone provide any insight on this? class myContainerComponent extends Component { constr ...

Challenges encountered while setting up Hotjar integration in Next.js using Typescript

I am encountering issues with initializing hotjar in my Next.js and TypeScript application using react-hotjar version 6.0.0. The steps I have taken so far are: In the file _app.tsx I have imported it using import { hotjar } from 'react-hotjar' ...

A tutorial on allowing a background element to capture the click event triggered by a foreground element

Within a container div, I have a background and foreground div. I want the click event on the foreground div to be passed through to the background div for handling the event. How can this be achieved in Angular 2+? Here is an example structure of my div ...

When I zoom in, my h1 tags shift to the right

I am relatively new to this and I am puzzled as to why the text inside my h1 tag seems to shift to the right when I zoom in. Below is the CSS code: h1 { font-family: 'Raleway', sans-serif; border-bottom: 1px solid black; border-top: ...

The height of each list item should expand based on the size of the div contained within it

The HTML markup I am working with looks like this: <ul data-role="listview" data-inset="true" class="stuff site-content lists"> <li> <div class="nearby"> 20 </div> <h1> name</h1> </li> ...

Passing a boolean value from Material UI Radio to utilize in Yup .when validation

Yup offers the ability to validate based on another value using .when. For example: var inst = yup.object({ isBig: yup.boolean(), count: yup .number() .when('isBig', { is: true, // alternatively: (val) => val === true ...

In the context of React Typescript, the term 'Component' is being mistakenly used as a type when it actually refers to a value. Perhaps you intended to use 'typeof Component' instead?

Looking to create a routes array and apply it to useRoutes in react-router@6. I am currently using TypeScript and Vite. However, I encountered an error when attempting to assign my component to the 'element' key. type HelloWorld = /unresolved/ ...

Error: `this.context.router` is undefined in React

I have encountered an issue in my home page component where this.context.router is not defined. The dependencies I am using include: "@material-ui/core": "^3.9.3", "@material-ui/icons": "^3.0.2", "history": "^4.9.0", "moment": "^2.24.0", "prop-types": "^1 ...

Error: The property 'scrollIntoView' cannot be read because it is null

class MessageApp extends Component { constructor(props) { super(props) this.state = { text: "", messages: [] } } componentDidMount() { const config = { apiKey: "<api-key>", authDomain: "<projec ...

Error: Unable to locate module: Unable to resolve './Page.module.css' in Next.js version 13

When I run npm run build on Vercel and Heroku, I encounter an error that does not occur on my local computer: The error message is Module not found: Can't resolve './Page.module.css' I am trying to import this file from app/page.tsx, and b ...