What is the best method for passing page props in Next.JS?

One example is using the React Context API to pass props from the _app file to pages.

Another scenario involves refactoring a ReactJS routing, where state is passed from app.js to pages through the route definition as shown below:

<Route><Component state=state/></Route>

The documentation I came across here suggests that we should avoid touching the pageProps since it is intended for statically generated props only.

Here's a specific piece of code that needs attention:

const App = (Component, pageProps) => {
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [products, setProducts] = useState([]);
  const [cart, setCart] = useState({});
  const [order, setOrder] = useState({});
  const [errorMessage, setErrorMessage] = useState('');

  // Other functions and hooks

/* switch (useRouter.pathname) {
  case ('/shop'):return <Products products={products} onAddToCart={handleAddToCart} handleUpdateCartQty />
  case ('/cart'): return<Cart cart={cart} onUpdateCartQty={handleUpdateCartQty} onRemoveFromCart={handleRemoveFromCart} onEmptyCart={handleEmptyCart} />
  case ('/checkout'):    return    <Checkout cart={cart} order={order} onCaptureCheckout={handleCaptureCheckout} error={errorMessage} />
}
 */

  return <Component className="App" {...pageProps} />
}
export default App

Answer №1

Instead of the routing system, you can opt for a switch statement:

Here's how it looks in your example:

import {useRouter} from 'next/router'
[...]
switch (router.pathname) {
    case "/shop":
      return (
        <div style={{ display: "flex" }}>
          <CssBaseline />
          <Navbar
            totalItems={cart.total_items}
            handleDrawerToggle={handleDrawerToggle}
          />

          <Products
            products={products}
            onAddToCart={handleAddToCart}
            handleUpdateCartQty
          />
        </div>
      );
    case "/cart":
      return (
        <div style={{ display: "flex" }}>
          <CssBaseline />
          <Navbar
            totalItems={cart.total_items}
            handleDrawerToggle={handleDrawerToggle}
          />

          <Cart
            cart={cart}
            onUpdateCartQty={handleUpdateCartQty}
            onRemoveFromCart={handleRemoveFromCart}
            onEmptyCart={handleEmptyCart}
          />
        </div>
      );
    case "/checkout":
      return (
        <div style={{ display: "flex" }}>
          <CssBaseline />
          <Navbar
            totalItems={cart.total_items}
            handleDrawerToggle={handleDrawerToggle}
          />

          <Checkout
            cart={cart}
            order={order}
            onCaptureCheckout={handleCaptureCheckout}
            error={errorMessage}
          />
        </div>
      );
  }

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

A guide on trimming content with v-if in Vue.js

Recently, I attempted to trim the response value within a Vue condition. I require this functionality to apply the condition when the value is null or empty. <li v-if="item[0].otrodl4.trim() == ''" class="progress-step"> ...

Guide to accessing object items in v-for in VueJs

Upon inspection, the following results are being displayed: In the Vue template code provided: <select class="form-select" v-model="post_format.wpml_language"> <option v-for="(lang, index) in wpml_languages" :value="lang">{{lang}} {{index}} ...

The HTTP GET request in Express.js is throwing a 500 internal server error

I have implemented a GET API call to retrieve all users from my Logins database. However, I keep encountering 500 errors when making the request. Below is the code snippet I am using: const http = axios.create({ baseURL: "http://localhost:8080/api ...

Issue with Datatables FixedColumns plugin in IE8/7 and Firefox

I am encountering issues with the FixedColumn plugin on IE8, IE7, and Firefox. All of them are causing my table to malfunction, displaying the following error: Error: Invalid argument. Line: 566 Char: 3 Code: 0 URI: ./resources/javascript/dataTable/Fixed ...

Can the value of a key be changed to match the condition in a find() query when using Mongoose?

Having been well-versed in Oracle, I was thrown into a project requiring the use of a MongoDB database. Utilizing mongoose to connect to my MongoDB, my main query is whether it is possible to match a find condition before executing a query. For example, if ...

Access data from previous request and transmit it to another request in a Node.js environment

I am facing a situation where I need to extract the parsed json response from a variable in a POST request, store it in a new variable, and then pass that variable in the headers for a subsequent GET request. However, my current approach is not yielding th ...

Is Next.js the Ultimate Serverless Rendering Tool with Cloudflare Workers?

I am currently using Next.js version 9 and I am interested in utilizing Next's serverless deployment feature by integrating my application with Cloudflare Workers. According to the documentation for Next.js, all serverless functions created by Next f ...

Using either Javascript or JQuery to update every cell in a particular column of a table

I need to use a button to add "OK" in the Status column of table tblItem, which is initially empty. How can I achieve this using JavaScript or JQuery? The table has an id of tblItem Id Item Price Status 1 A 15 2 B 20 3 C ...

Typography splits into a second line within the grid on the toolbar

I need help with my Appbar design. I want to align the title (Lorem ipsum text) on the left and the buttons on the right. However, when I tried implementing the code below, I noticed that there seems to be a maximum width causing the text to break into t ...

Issue with Angular: Unable to update model before modal closure on submit

I have a search form that is displayed within a modal window created using Angular UI Bootstrap. The input fields in the form update the ng-model when submitted. <script type="text/ng-template" id="mobileSearchPanel"> <form> ...

Performing addition operations on numbers entered through an HTML input field using PHP

I am looking to create a feature where the numbers entered in an input form are added together. I need to store these numbers in an array and have them display in a new line when a button is clicked. Here is the HTML code for the input field and button: ...

Shading THREE.js Color with Textures

I have added a simple box to my scene, and I am looking to create a shader that will apply a texture to it and add color to this texture. Here is my vertex shader (nothing special about it): <script id="vertexShader" type="x-shader/x-vertex"> ...

I am looking to enhance the readability of my asynchronous function calls

At the moment, I am handling my Promises by calling an async function and then chaining it with .then(). But I feel like there could be a more readable approach. This is how it currently works: const fetchData = async() => { const response = await ax ...

I am experiencing issues with the HTTPClient call not returning accurate JSON data within my Appcelerator Titanium application

Every time I attempt to retrieve information from a JSON file, I encounter an error. function search(e){ var url = 'https://www.dotscancun.com/createjson.php?id=100001'; var xhr = Ti.Network.HTTPClient({ onerror: function(e){ ...

Recognize different HTML components when an event occurs

My application is equipped with a multitude of buttons, inputs, and other elements that trigger different events. I am looking for a way to easily differentiate between each element and the event it triggers. For instance, consider the following snippet f ...

selecting a div element with a label using the nth-child property

I recently discovered the CSS3 :nth-child() Selector and decided to create a sample Here is the HTML snippet: <body> <div> <label>dsdf</label></div> <div>seconddiv</div> </body> And here's the CSS par ...

How can I prevent having to repeat the getStaticProps function on multiple pages within NextJS?

Navigating React/NextJS as a newcomer has been a challenge, especially when it comes to handling file imports and requirements. For my project, I am utilizing getStaticProps for Static Site Generation (SSG) to fetch data from Prismic CMS. Referencing the ...

Interacting with a non-stringified object displayed in the browser console using TestCafe

Upon receiving a page that logs an object to the console, I encountered an issue when trying to access this object using getBrowserConsoleMessages(). The object appeared as the String "[object Object]" in the console, making it impossible for me to parse ...

Revealing Next.js Environment Variables for Integration with PWA's API System

As per the official documentation of Next.js, exposing an environment variable requires using the NEXT_PUBLIC_ prefix. However, in this case, the admin is utilizing process.env.REACT_APP_API_ENTRYPOINT. In order to access the REACT_APP_API_ENTRYPOINT envi ...

What is the best way to display a message on the 403 client side when an email sending fails?

I am attempting to display an alert message when the email is sent successfully or if it fails. If it fails, I receive a 403 status code from the backend. However, I am unsure how to handle this error on the client-side. In the case of success, I receive a ...