Ensure that the Map reference object is accessible when the first modal window is displayed or opened

My issue involves a table where selecting a row should display the item's location on a map using react-map-gl in a Dialog component. However, upon clicking the row, the mapref returns null during the initial render, even though it should provide mapref objects like flyTo() and setCenter(). This unexpected behavior occurs only when launching the Modal.

I've included the full code below for reference:

import "mapbox-gl/dist/mapbox-gl.css";
import { useCallback, useEffect, useRef, useState } from "react";

import MapGl, {
  FullscreenControl,
  NavigationControl,
  Marker,
  Popup
} from "react-map-gl";

export default function MapDialog() {
  // Functionality to handle the opening and closing of the Dialog
}

// More code here...

To better understand the issue and possible solutions, you can view the complete context by visiting this sandbox link:

Answer №1

Switched from using useRef() to useState and saw positive results; the re-render triggered by useState worked like a charm.

const [mapRef, setMapRef] = useState(null)

 useEffect(() => {
    if (mapRef) {
    mapRef?.setCenter({
      lat: rowData?.laty,
      lng: rowData?.longx
    });
   }
  }, [rowData,mapRef]);

<Map  ref={(ref) => setMapRef(ref)}/>

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

When directly called from index.js, Next.js getStaticProps and getInitialProps return undefined for a component

I've been following this tutorial: https://nextjs.org/learn/basics/data-fetching/implement-getstaticprops, but I decided to create a new component instead of adding the code directly to the index.js file. Although the tutorial's method works fin ...

Is there a way to access the useQuery refetch method in other components?

In my NextJS app, I have a functionality where the Header is rendered along with either the Homepage, Contacts, or About page: Here is a simplified version of the _app.tsx file: export default function MyApp({ Component, pageProps }: Props) { return ( ...

Displaying object properties in React and rendering them on the user interface

Within my React application, I am retrieving data from an API using the following code snippet: function PlayerPage() { interface PlayerDataType { id: number; handle: string; role: string; avatar: string; specialAbilities: null; s ...

Implementing a white color scheme for TextField forms using Material UI

Hi there! I'm a beginner in using Material UI with React and have two questions that I hope someone can help me with: I've been trying to figure out how to set the color of the TextFields (the input fields) to white. Currently, the placeholder ...

Exploring the capabilities of X-grid within Material v5

I have been working on a React app using the latest v5 alpha version of material-ui. The documentation mentions that 'The data grid components support both v5 and v4'. However, when I tried to import X-grid, I encountered this error: ./node_mod ...

Retrieving external parameters within an internal map within a dynamically created array of elements

I'm attempting to retrieve an array of elements within a JSX template from a nested object in this manner: <Menu id="menu-locations" anchorEl={this.state.anchorElLocationsMenu} anchorOrigin={{ vertical: 'top', ...

A guide to resolving the Prisma Unique Type error while deploying on Vercel

After successfully running the app in my local development environment, I encountered an unexpected type error upon deploying to Vercel. My tech stack includes Next.js, Prisma, and tRPC. Any suggestions on what could be causing this issue? Link to Code ...

Can you explain the distinction between these two forms of functional components in ReactJs?

What sets apart these two code usages? In the FirstExample, focus is lost with every input change (It appears that each change triggers a rerender).. The SecondExample maintains focus and functions as intended. example import React, { useState } from &quo ...

Upon initiating a React Native project, five critical vulnerabilities become apparent

Upon starting my React Native project, I encountered 5 high severity vulnerabilities. Despite attempting to fix them with the command "npm audit fix --force", the issue persisted. I even went as far as reinstalling node.js and React Native, but the vulne ...

The CORS policy has blocked the 'Access-Control-Allow-Origin' header

My expertise lies in creating API, BackEnd, and Frontend websites. For the API, I utilize Express, while for the BackEnd - FrontEnd, I rely on ReactJs. During local testing, everything functions as expected. However, upon deployment to the server, error ...

Having trouble understanding JSON data in React, unsure if I have made any conceptual mistakes

I'm currently utilizing the MaterialUITable to showcase tabular data, all within the confines of React as my primary framework. Fetching a JSON file from a parallel root directory is part of my workflow, with an aim to exhibit the information stored ...

A guide on utilizing React hooks to randomly divide a group into two teams

Is there a way to randomly divide players from an array into two teams, ensuring that each team has an equal number of players if the total is even. If it's an odd number, having one extra player in either team is acceptable. I have written a JavaScr ...

Error message: Act must be used when rendering components with React Testing Library

I am facing difficulty while using react-testing-library to test a toggle component. Upon clicking an icon (which is wrapped in a button component), I expect the text to switch from 'verified' to 'unverified'. Additionally, a function ...

Purge all form data upon submission using React.js

I have the following React code snippet in my app and I am looking for a way to clear input fields after submitting the contact form. My approach involves utilizing ref and triggering the handleSubmit function when the form is submitted. import { useRef } ...

Having trouble toggling between the trending and search features on giphy website

I've been developing a chat application with NextJS and I'm currently working on integrating GIPHY images into it. Although I have the basic setup in place, I'm facing issues when switching between the giphy.search() and giphy.trending() fu ...

The image source failed to load the image using the function

Initially, I set up a sandbox to work on this issue: https://codesandbox.io/s/naughty-almeida-u66mlt?file=/src/App.js The main problem arises when the requested image fails to display after the function is called and the URL is returned. Here are my atte ...

Exploring the power of React Leaflet and the exciting possibilities of React Leaflet

I'm currently in the process of implementing the draw functions on a leaflet map. I started off by creating a new app with just react-leaflet installed. I used npx create-react-app and installed the following packages: npm install react react-dom lea ...

Navigating Sockets with Navigator in React Native

Every time I encounter the error message undefined is not an object (evaluating this.props.socket.on). In my code, I define the socket in the index.ios.js file as shown below: class Main extends Component { constructor(props) { super(props); ...

What causes certain components in ReactJs to not respond to the `:focus` pseudo-class?

Currently, I am in the process of implementing a straightforward Emoji-Rating system where 5 emojis are displayed on the screen and upon hovering over them, their appearance changes. This functionality is achieved using the :hover pseudo-class. My goal is ...

Is it possible to incorporate MUI React components within an iframe?

Looking to replicate the style seen in this Material UI website screenshot, I aim to design a container that will encompass my iframe contents, such as the navBar and menu drawer. However, I want to utilize Material UI's components for these elements. ...