Passing Data Between Page and Component (NEXT.JS + LEAFLET Integration)

I have recently started using Next.js with Leaflet maps and have encountered a beginner's question. I created a page in Next.js ( /pages/map/[id].jsx ) that utilizes a component ( /component/Map.jsx ).

Within the page ( [id].jsx ), I fetch a JSON file containing various values, including the "Latitude and Longitude". I need to pass these values to the component ( Map.jsx ) to display the map with those coordinates on the page.

Each post on the page ( [id].jsx ) has different values. I am unsure of how to pass these values to the component.

My knowledge of React and Next.js is quite basic, and despite searching online, I have been unable to find a solution. Can anyone provide me with some guidance? Thank you in advance.

Code from file [id].jsx

import Image from "next/image";
import dynamic from "next/dynamic";

export default function soloRefugio({ data }) {

  return (
    <Layout>
      <article>
        <Image
          priority
          src={data[0].Imagen.name}
          height={400}
          width={400}
          alt="imagen"
        />
        <h1>{data[0].Nombre}</h1>
        <p>P: {data[0].Pro}</p>
        <p>A: {data[0].Alt}</p>
      <MapBox />
      </article>
    </Layout>
  );
}

function MapBox() {
  const Map = dynamic(
    () => import('../../components/Map'),
    { ssr: false }
  )
  return <Map />
}


export async function getStaticPaths() {
  try {
    const res = await fetch("http://localhost:1337/ref");
    const data = await res.json();
    const paths = data.map(({ slug }) => ({ params: { id: slug } }));

    return {
      paths,
      fallback: false,
    };
  } catch (error) {
    console.log(error);
  }
}

export async function getStaticProps({ params }) {
  try {
    const res = await fetch("http://localhost:1337/ref?slug=" + params.id);
    const data = await res.json();
    return {
      props: {
        data: data,
      },
    };
  } catch (error) {
    console.log(error);
  }
}

Code from file component Map.jsx

import { MapContainer, Marker, Popup, TileLayer } from 'react-leaflet'
import 'leaflet/dist/leaflet.css'

const Map = () => {

  return (
    <MapContainer center={[51.505, -0.09]} zoom={13} scrollWheelZoom={false} style={{height: 400, width: "100%"}}>
      <TileLayer
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      <Marker position={[51.505, -0.09]}>
        <Popup>
          A pretty CSS3 popup. <br /> Easily customizable.
        </Popup>
      </Marker>
    </MapContainer>
  )
}

export default Map

Answer №1

Exploring the guidance provided in Next's dynamic routes' documentation, it is evident that utilizing the useRouter hook enables retrieval of query parameters passed to the route.

In this scenario, enhancing the soloRefugio component could involve the following addition:

const router = useRouter()
  const { id } = router.query

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

Automatically updating the results section while executing SQL queries in PHP

Here is a JavaScript/Ajax code snippet: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready (function () { var updater = se ...

Tips for maintaining pagination state in datatable when making ajax calls

Summary of my question How can I keep the datatable on the same page after updating a row using ajax in my unique way? Challenges I'm facing When a user clicks a button in the table to update a specific row and I call the fn_GetData() function. Af ...

Avoid running multiple YouTube views simultaneously within an AngularJS application

Currently, I have an Angularjs application that displays a list of Youtube videos utilizing the videogular node module. An issue has arisen where users can play multiple Youtube videos simultaneously, leading to potential violations of Youtube's poli ...

Experiencing a deployment issue with Heroku: getting a npm error stating "Host key verification failed" while trying to deploy a

I am currently facing an error while trying to deploy my Next.js/Express.js backend app on Heroku via GitHub. The specific error message I keep encountering is as follows: Any assistance in resolving this issue would be greatly appreciated! Thank you. h ...

How can you animate the background of a website using AngularJS - CSS or JavaScript?

My aim is to create a dynamic animation for the background image when the view changes. The current background image is set through a function defined within MainController: // app/js/controllers.js $scope.getBg = function() { return $route.current.sco ...

Struggling with mapping through a multidimensional array?

I'm facing an issue with using .map() on a nested array. I initially tried to iterate through my stored data using .map(), and then attempted another iteration within the first one to handle the nested array, but it didn't work as expected. The ...

Tips for duplicating a collada model in three.js?

I've imported a .dae model into my scene and I want to use it multiple times. The code provided works with meshes, but the collada.scene object is not a mesh: var mesh2 = new THREE.Mesh( loadedMesh.geometry, loadedMesh.material ); Is there a way to ...

Managing numerous range sliders in a Django form

My Request: I am looking to have multiple Range sliders (the number will change based on user selections) on a single page. When the sliders are moved, I want the value to be updated and displayed in a span element, as well as updating the model. The Issu ...

Learn how to easily upload multiple files from various upload points onto a single page using Node.js and express-fileupload

After searching on various platforms, including StackOverflow, I couldn't find a solution that fits my specific scenario. I've been struggling for hours to resolve this issue... In my handlebars page, there is an option for the user to upload fi ...

Changing the caret position in a contenteditable div using HTML React

In a recent project I worked on, I included contenteditable divs. Whenever the enter key is pressed within one of these divs, it splits into two separate contenteditable divs. However, after React re-renders the components, the caret tends to go to the beg ...

After successfully authenticating, you may introduce a new React component

Currently, I am working on a page that will only display information once a user has logged into their account. I have successfully implemented an authentication system using NodeJS, and now my goal is to restrict access to specific components or pages bas ...

What is the most effective method for transferring resolved promise values to a subsequent "then" chain?

Currently, I am grappling with understanding promises by utilizing the Q module in node.js. However, I have encountered a minor setback. Consider this scenario: ModelA.create(/* params */) .then(function(modelA){ return ModelB.create(/* params */); } ...

Script for uploading multiple images without using flash, with customization options available for each individual upload

Looking for a non-flash images uploader script that has the following features: Ability to upload multiple files Supports drag and drop functionality Displays progress bar for each upload Shows small preview of each upload Allows for resumable downloads ...

What is the best way to upload an object in React using fetch and form-data?

Currently, I am facing an issue where I need to send a file to my express app as the backend. The problem lies in the fact that my body is being sent as type application/json, but I actually want to send it as form-data so that I can later upload this file ...

"Utilize Node to import either all dependencies or selectively choose specific

Should we only require the specific properties we need or the entire object? Example: Below is a snippet from my helper file 'use strict'; /** * getCallback * return a function used to make callback * @param {callback} callback - the callb ...

Exploring the functionality of Angular.js through QUnit testing

Is it possible to integrate angular.mock.inject() with QUnit instead of Jasmine? In the provided code snippet, angular.mock.dump is defined, but unfortunately angular.mock.inject remains undefined. <!DOCTYPE html> <html ng-app="mymodule"> & ...

The URL for the dynamic import in Workbox is loading incorrectly

For my laravel/vuejs application, I am utilizing workbox and babel dynamic imports. Additionally, I am making use of the laravel-mix and laravel-mix-workbox plugin to compile and generate service worker via generateSW(). The assets load correctly on the r ...

Is there a way for me to retrieve the element that is linked to the ng-disabled attribute?

Is there a way to access the element with the ng-disabled attribute inside the function without passing it as a parameter? Here is the HTML element: <input class="needsDisabling" ng-disabled="isFieldDisabled()" type="text"> The isFieldDisabled fu ...

Angular JS: Distribute objects from a single array to various arrays or services

I have recently embarked on developing a basic app using Angular JS, utilizing a service/factory to manage data and enable the addition of objects. Within the array of various individuals (listed in the html), you can include them as candidates by employi ...

Designing an advanced remote upload system using jQuery AJAX and PHP

Currently, I am in the process of developing an image hosting script and everything is going smoothly so far. To enable local uploading with drag & drop + AJAX, I have utilized various plugins which are working perfectly. Now, I am moving on to implementin ...