Navigating through routes and selecting one item from an array in real-time

In my data.js file, I have an array called 'product' containing the values 'name' and 'path'. The page URL is identified by 'path'

data.js

export const product = [{name:Processor,      path:processor},
                        {name:Graphics Card,  path:graphics-card}]

My Index page

index.js
-------------

import { product } from "data";

export default function Builder({ children }) {
return(
<>
<Navbar>
{product.map((item) => (
           <li key={item.path}>
             <Link href={`/products/${item.path}`} >
               <a><span >{item.name}</span></a>
             </Link>
          </li>
        ))})
</Navbar>
{children}
</>

}

The [product] page is dynamically generated.

My folder structure

data.js
index.js
products/
 [product].js

[product.js]
------------

import Builder from "./index"

export default function Product() {
  return (
    <>
    <Builder>

        //I need to display 'product-name' here.

    </Builder>
    </>
  )
}

When using 'router.query', only the 'product-path' is visible. Each page should actually display the corresponding 'product-name.'

I'm new to next.js, so any guidance on finding a solution would be greatly appreciated.

Answer №1

Initially, ensure that the values of your objects in the product.js file are designated as strings, such as "Graphics Card", rather than simply Graphics Card.

Typically, we generate new data requests based on dynamic URL segments. In this scenario, it could appear something like this within your product.js file.

import { useRouter } from 'next/router';
import { useState, useEffect } from 'react';

import Builder from './index';
import { product } from 'data.js';

export default function Product() {
  const [currentProduct, setCurrentProduct] = useState('');
  const router = useRouter();
  const { path } = router.query;

  useEffect(() => {
    const item = product.filter((item) => item.path === path);
    setCurrentProduct(item[0].name);
  }, []);

  return <Builder>{currentProduct}</Builder>;
}

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

I can't figure out why my SCSS isn't loading, even though I've added it to the webpack.mix.js file in my Laravel project that's set up with React.js

I'm facing a problem where my SCSS is not loading in the VideoBackground.js component of my Laravel project built with React.js, even though I have set it up correctly in the webpack.mix.js file. The file path for the videoBackground.scss file within ...

How can I delete a date value from a td if it matches the current date value?

I'm facing an issue with duplicate date values in my table rows and trying to find a solution using JavaScript or JQuery. The problem cannot be fixed within the SQL query itself, so I need to explore alternative approaches. I want to remove repeated d ...

Inquiring about the specifics of pointer behavior

Consider having an array int b[] = {2, 3, 4}; What allows a pointer to the first element &b[0] to point to elements of the array or values in general, while the pointer &b itself cannot? cout << (&b[0])[1]; // 3 cout << (&b)[0 ...

Challenges with JavaScript calculations on dynamic HTML forms

Currently, I am immersed in a project focused on creating invoices. My progress so far involves a dynamic form where users can add and remove rows (as shown in the snippet below). I'm encountering an issue with my JavaScript and I could use some ass ...

Converting a JSON Array Object into PHP script

I need to send this JSON Array from my Android app to a PHP script. I successfully sent the json with one element ('CABECERA'), but now I am struggling with parsing it in my php script. How can I recreate an entire CABECERA object from this json ...

Modify every audio mixer for Windows

Currently working on developing software for Windows using typescript. Looking to modify the audio being played on Windows by utilizing the mixer for individual applications similar to the built-in Windows audio mixer. Came across a plugin called win-audi ...

Tips for embedding React components, kept in an array, within the render function of a separate component

I have a component called Screen that imports another component to display search results. Within the Screen component, there is a method that loops through an array of objects and creates new instances of the search result component for each object. As I ...

When working with JavaScript, it's important to note that any reference used outside of the catch block

Our JavaScript code includes a try...catch block that functions as follows: We import the customFile using: const ourCustomClassFile = require('./customFile'); In the customFile.js file, we have defined a function const sendErrorNotification ...

Can you explain the significance of this HTML code?

While examining some source code, I came across the following: <div class="classname {height: 300px; width: 200px}"></div> I am aware that element styling can be done using the style="" attribute. Could you explain what this code snippet sig ...

Tips for displaying AJAX response data on a webpage

I am currently developing a Spring Boot application that includes a website with a submenu featuring various computer games. My goal is to have the server respond by sending an image (specifically a path to the image) of the selected game when a position i ...

Express displays HTML code as plain text

I am currently facing an issue where I am trying to display an html table on /guestbook.ejs and then redirect it to /guestbook. However, the content of my guestbook.ejs file is being displayed as plain text rather than rendering the HTML code. Below is th ...

Is Immutable state considered a key functional aspect in the ReactJs framework?

One key aspect of an imperative program is the emphasis on state and its modifications. When it comes to ReactJs, there is a push for more functional programming styles, such as using purity and higher-order functions. I'm curious to explore whether ...

How can one effectively conceal the navigation bar on specific pages within a React application that implements React Router?

I am working on my react app and I have a requirement to hide the Navbar specifically for the PageNotFound component. import React, { Component } from 'react'; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; i ...

What makes it essential to use jasmine's runs and waitFor function?

My current task involves testing an asynchronous code snippet structured like this: randomService.doSomething().then(function() { console.log('The operation has been completed!'); }); Interestingly, I've noticed that the success messag ...

Adjust the positioning of a class element

I have an eye icon that changes position when clicked. Initially, it is set to left: 10%;, but if there is a DOM element with the ID login-section, it should be repositioned to left: 50%;. I attempted to use document.getElementsByClassName('fa-eye-sl ...

Determine the mean of an extensive array with numerous elements

Is there a way to calculate the average of over 200 long values stored in an array in Java without running into limitations due to the size of the numbers? Typically, you would add all the values and divide by the total count, but what if the number is t ...

Hide an absolutely positioned div when another element is clicked outside of it

Here is the code for the function that executes when a button on my website is clicked: function displayOverlay() { document.getElementById("overlay").style.visibility = "visible"; document.getElementById("dim").style.visibility = "visible"; d ...

Button within the Magnific Popup (do not use to close)

I am currently developing a website with a gallery page that utilizes the Magnific Popup plugin. My client has provided lengthy 'captions' for each image, almost like short stories. To display these captions effectively, I have utilized the titl ...

Implement Video Quality Controls for HLS.js and Video.js during Live Streaming

Exploring HLS.js (() => { var video = document.getElementById('video'); console.log('VIDEO', video); if (Hls.isSupported()) { var hls = new Hls(); hls.loadSource('https://te ...

PHP Combining array items with the following item without changing their sequence

$array = ['sprite.','pepsi.','ice cream.']; foreach ($array as $index => $value) { if (strlen($value)<6) { $new[] = $value." ".$array[$key+1]; } else { $new[] = $value; } } Unfortunately, the code ab ...