Exploring the concept of importing components from different pages in NextJS

I'm currently navigating the Next.JS framework and struggling to grasp the concept of importing data from a component page. Let's say I've created a page named example.js in my components folder, where I'm fetching data from an API to display on a graph. However, when I try to render this graph in my index.js file, I encounter an 'Unhandled Runtime Error' because the API function in example.js is not being called.

Here is how I'm importing the page in /pages/index.js:

import dynamic from 'next/dynamic'
const Example = dynamic(() => import('../pages/example.js'))

//Later on inside my return
  <Example />

In my example.js page, I export like this:

function Example(props) {
  return <div>
    ...my code
  }

And at the end of example.js, I have:

export default Example

This is followed by the getStaticProps function:

export async function getStaticProps() {
  const res = await fetch("")
  const data = await res.json()

  if (!data) {
    return {
      notFound: true
    }
  }

  return {
    props: {
      data: data.reverse(),
    },
  }
}

If I use this exact setup in my index.js, everything works as expected. So why isn't it working in practice? Any thoughts on what might be causing this issue and how to resolve it?

Edit for clarity: My getStaticProps function resides in the example.js file, but it seems that it's not being triggered when needed.

Answer №1

When it comes to handling server-side rendering, static-site generation, and code splitting in Next.js, there's a touch of magic involved. The unique aspect is that all this sorcery happens right within the /pages folder. It's worth noting that components residing in the /pages directory function slightly differently from typical React components. Here are some valuable tips that might just be the solution to your current dilemma.

1. Place your page components inside the /pages folder.

Components housed in this specific folder can have a default export (the component) along with named exports (such as the special Next.js functions like getStaticProps). Should Next.js detect these exported functions, it will proceed to execute them.

2. Reserve next/dynamic solely for dynamic imports.

Dynamic imports facilitate lazy loading, which has implications on both Next.js' automatic code-splitting and potentially server-side rendering capabilities. While I may not possess the full understanding of its inner workings, my hunch suggests that dynamically loading a Page component (given their uniqueness in Next.js) could be the source of the issue at hand. Personally, I tend to resort to dynamic imports only when dealing with third-party components that disrupt SSR, necessitating their exclusion from server-side rendering through dynamic importing.


Perhaps the simplest approach to tackle this would be:

within /pages/index.js:

import Example from '../path/to/example';

export default (props) => (
  <div>
    <p>My page component</p>
    <Example />
  </div>
);

export async function getStaticProps() {
    return {
        props: {
            data: // ...
        }
    };
}

In the scenario above, you may incorporate dynamic imports too -- what holds significance is the immediate exportation of your Next.js-specific function straight from the file within /pages:

inside /pages/index.js:

import dynamic from 'next/dynamic';

const Example = dynamic(() => import('../components/example'));

export default (props) => (
  <div>
    <p>My page component</p>
    <Example />
  </div>
);

export async function getStaticProps() {
    return {
        props: {
            data: // ...
        }
    };
}

To address the concern regarding "My getStaticProps function is in my example.js file, and my issue is that it is not being triggered.":

It's crucial to recognize that Next.js exclusively triggers a getStaticProps function if it's exported from a file within the /pages directory. If you intend to define your getStaticProps method outside of this directory, it's indeed feasible; however, you must import it into /pages and subsequently re-export it as follows:

within /components/example.js:

export default () => (
    // ... component ...
);

export function getStaticProps() {
    // ... function ...
};

furthermore, inside /pages/index.js:

import Example, { getStaticProps } from '../components/example';

export default Example;

export {
    getStaticProps
}

This methodology should prove effective. Nevertheless, it's important to note that in this context, you cannot leverage dynamic imports for Example.

Answer №2

This response is outdated and it's now advised to implement App Router instead. https://nextjs.org/docs#app-router-vs-pages-router

While pages can still be utilized, it's strongly recommended that new projects should utilize the App Router.

Therefore, use /app instead of the /pages folder.

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

iOS Simulator offers a range of both offline and online events for testing purposes

I have been working on a phonegap 3.3 application that incorporates angularjs. When testing the application in my browser, I am successfully able to detect and respond to 'offline' and 'online' events. However, when I switch to the ios ...

Error message: "Error encountered while building Next.js - ReferenceError: 'describe' is not defined"

I am facing difficulties achieving a successful next build without encountering the following error: > Build error occurred { ReferenceError: describe is not defined Although the dev server and tests execute smoothly, it appears that the jest global d ...

Modify the css of the initial div following a live click

After clicking on the span.submit-comment, I am looking to modify the CSS of a specific div. Can anyone advise me on how to achieve this? I attempted to change the background color of the div in the success section of the script like so: $('div.new ...

Dynamically assigning a name to a variable through code

Is there a quicker way to complete these 100 tasks? variable_1 = 1; variable_2 = 2; variable_3 = 3; ... variable_100 = 100; I attempted to use the following code: for(var i = 1; i <= 100; i++) { variable_ + i = i; } However, I encountered an e ...

What is the best approach to dealing with "Cannot <METHOD> <ROUTE>" errors in Express?

Here is a simple example to illustrate the issue: var express = require('express'); var bodyparser = require('body-parser'); var app = express(); app.use(bodyparser.json()); app.use(errorhandler); function errorhandler(err, req, res, ...

Jest encountered difficulty in parsing the file import code

I'm currently in the process of testing my Next.js project with Jest and Enzyme. However, I've encountered an issue when attempting to import a file from my components for testing purposes. Below are snippets of my configuration files... My jest ...

Update the data-value parameter dynamically after a successful Ajax request without utilizing the element's

I have a bunch of different buttons to switch the status of various projects: <div class="btn-group btn-toggle project_status" data-project-id="1" data-form="project_status" data-value="1"> <button class="btn btn-default active">ACTIVE</ ...

Transforming timestamps to month day, year format and back again without the use of any NPM packages

I have developed a microservice that converts Unix timestamps to a format like Dec 01, 2017 and vice versa. The microservice is deployed at this link: timestamp I am wondering if there is a better way to achieve this without using third-party NPM modules. ...

Discover the geolocation data for post code 0821 exclusively in Australia using Google Maps Geocoding

I'm having trouble geocoding the Australian postcode 0821. It doesn't seem to reliably identify this postcode as being located within the Northern Territory, unlike 0820 and 0822 which work fine. Here's an example of what I'm doing: ...

Refreshing a page following an AJAX request made with jQuery

I am working on a JSP page that shows student details. When a student is selected from the dropdown box, it triggers an onchange event to retrieve the minimum and maximum marks for that student. <form name="listBean"> <c:forEach var="Item" i ...

What is the best way to access data from this $scope in AngularJS?

Upon printing selecteditems to the console, this is the output: [{"model":"Lumia","brand":"Nokia","subModel":["Lumia 735 TS","Lumia 510"],"city":"Bangalore"}] I have stored it in $scope.details as follows: var selecteditems = $location.search().items ...

Generate a loop specifically designed to execute the code following the menu in the script

My website has the code snippet below: let txt_com = document.querySelector(".text_user"); let num_com_user = document.querySelector(".massage_for_user"); txt_com.addEventListener("click", function() { if (this.classList.contains("num_com_user")) { ...

Retrieve the number of days, hours, and minutes from a given

Is it possible to use JavaScript (jQuery) to calculate the number of days, hours, and minutes left before a specific future date? For example, if I have a timestamp of 1457136000000, how can I determine the amount of time remaining in terms of days, hours ...

What is the process for taking a website project running on localhost and converting it into an Android web application using HTML, CSS, and JavaScript

Looking for recommendations on how to create an Android web application using HTML, CSS, and JavaScript. Any suggestions? ...

Refresh the array using Composition API

Currently, I am working on a project that utilizes Vue along with Pinia store. export default { setup() { let rows: Row[] = store.history.rows; } } Everything is functioning properly at the moment, but there is a specific scenario where I need to ...

The Json parsing failed to deserialize the API response

Struggling to send a JSON to my API, I've tried various solutions but still can't figure out what's going wrong. I'm stuck on this post call function: @PostMapping(path = "ts/sts") public void saveTestStep(@RequestBody Tes ...

Show items in the sequence of clicking

Is there a way to display elements in the order they're clicked, rather than their order in the HTML using jQuery? For example: CSS code: .sq{ display:none; } HTML Code: <a href="#" id="1">A</a> <a href="#" id="2">B</a> ...

Transform large GeoJSON files into TopoJSON format

I am struggling to convert a large GeoJSON file that is approximately 1.4GB in size. The command line tool is unable to handle the file due to its filesize. I typically use the topojson command tool like so: topojson {{ input file }} >> {{ output fi ...

Eliminating rows from a DataTable through an Ajax request

I have a DataTables table from datatables.net with a custom column containing icons for various actions. One of these actions is deleting a row without reloading the data. I'm looking for a built-in function to remove datatable rows locally after dele ...

Automated downloading based on operating system recognition

1067/5000 How can I use JavaScript to automatically determine the user's operating system on a webpage and then download the correct installation file? Here is the code I have: HTML <!DOCTYPE html> <html> <body> <iframe id=" ...