Mapbox map rendering problem in React with 100% high resolution

Currently working on rendering a map using Mapboxgl, Bootstrap 4, and React.

The goal is to make the map take up 100% of the page height and display in the first column of a two-column grid.

However, there's an issue when using React where the width of the map extends beyond the first column and overlaps with the second column.

To better visualize the problem, check out these examples on jsfiddle:

Map displaying correctly (without React) https://jsfiddle.net/apphancer/jhxy5c63/

Map width issue (with React) https://jsfiddle.net/apphancer/9g71ovn6/

To address the height issue, I am applying the following CSS:

.map-wrapper {
    position: fixed;
    width: 100%;
    height: 100%;
}

#map {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
}

The problem seems to be related to how the map renders with React since it works fine with pure HTML.

Looking for guidance on how to resolve this issue. Any insights?

HTML

<div id="app"></div>

CSS

body, html {
    height: 100%;
}

#app, .row, .col-9 {
    height: 100%;
}

.col-3 {
    background-color: rgba(0, 0, 0, 0.5);
    border: 1px solid red;
}

.map-wrapper {
    position: fixed;
    width: 100%;
    height: 100%;
}

#map {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
}

JS

mapboxgl.accessToken = 'pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4M29iazA2Z2gycXA4N2pmbDZmangifQ.-g_vE53SD2WrJ6tFX7QHmA';

class Application extends React.Component {
    componentDidMount() {
        const map = new mapboxgl.Map({
            container: 'map', // container id
            style: 'mapbox://styles/mapbox/light-v9', // stylesheet location
            center: [13.392, 52.523], // starting position [lng, lat]
            zoom: 9 // starting zoom
        });
        map.addControl(new mapboxgl.NavigationControl());
        map.resize(); // tried with this to see if it would help
    }

    render() {
        return (
            <div className="row no-gutters">
                <div className="col-9">
                    <div className="map-wrapper">
                        <div ref={el => this.mapContainer = el} id="map"/>
                    </div>
                </div>
                <div className="col-3">
                    2 of 2
                </div>
            </div>
        )
    }
}

ReactDOM.render(<Application/>, document.getElementById('app'));

Answer №1

By applying position fixed with 100% width to the wrapper, it will span across the entire width of the container. However, if you change the position to relative, it will only occupy the remaining space.

.map-wrapper {
    position: relative;
    width: 100%;
    height: 100%;
}

This method was successful in your react-jsfiddle. Feel free to give it a try.

Answer №2

If you're utilizing the fixed position in your project, it has the capability to cover the entire area. In such cases, there are two viable solutions:

First solution:

Allocate a 75% width to the #map element so that it mimics the behavior of col-9, rendering the need for position: absolute; unnecessary.

#map {
    width: 75%;
    height: 100%;
}

Second Solution:

Assign a relative position to the parent element of your component to confine its movement within that area. This involves changing position: fixed to position: relative.

.map-wrapper {
    position: relative;
    width: 100%;
    height: 100%;
}

Both solutions are effective but personally, I favor the second solution.

Answer №3

let [mapSize, setMapSize] = useState({ width: '100%', height: 'calc(100vh - 162px)', // Adjusted for elements overlaying the map latitude: 0, longitude: 0, zoom: 12, bearing: 0, pitch: 0, transitionDuration: 2000, transitionInterpolator: new FlyToInterpolator(), });

Answer №4

After transitioning to React 18 and performing updates on various dependencies, I integrated the map library.

The issue at hand was finally resolved by implementing this particular solution. There is a slight glitch when the map adjusts its size, but it's a step in the right direction.

useEffect(() => {
    map.on("load", () => map.resize());
}, [])

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

JQuery - stylish vertical accordion navigation menu

I'm currently working on a vertical accordion-style sidebar navigation system. Everything seems to be functioning properly, but I've encountered some issues with the icons that I'm using from Twitter Bootstrap 3. You can view the code on th ...

Adjust the size of the input form

Trying to create this design: https://i.sstatic.net/rPSiN.png But currently stuck with this layout: https://i.sstatic.net/3k5bE.png I'm puzzled on how to resize the input field with an icon on the right while using col-md-12... Check out my code ...

Having difficulties with hovering over a td that has a rowspan

I am encountering some challenges when attempting to hover over a td with rowspan in my HTML table. Despite searching for a solution, I have not been successful. I came across suggestions on forums that hinted at using JS/jQuery. Could someone please provi ...

Determining the best use-case for a React framework like Next or Gatsby versus opting for Create React App

As I delve into the world of React and JavaScript, I find myself in the fast-paced prototyping stage. I can't help but ponder at what point developers choose to utilize frameworks like Next.js or Gatsby.js over the usual Create React App. I'm pa ...

Images that are automatically generated cannot be interacted with by clicking on them

I currently have 4 images loaded onto my website. Whenever I click on one of the images, it becomes highlighted as desired using the following code: JavaScript Function 1 : var ImageSelector = function() { var imgs = null; var selImg = null; retu ...

Can you tell me the CSS equivalent of the SASS/SCSS expression "&$"?

Hey there! I've been diving into the world of Material-UI components and stumbled upon this interesting styling snippet: root: (0, _extends3.default)({}, theme.typography.subheading, { height: theme.spacing.unit * 3, boxSizing: 'content- ...

How Pivot Tables Function in Excel

Lately, I've been diving into the world of pivot tables in Excel and other spreadsheet programs. The idea has inspired me to consider developing a similar tool on the web platform using ReactJS. After doing some research online, I stumbled upon . Howe ...

What is the best way to align two buttons side by side when they are each contained in separate forms?

Is there a way to align the submit buttons in two separate forms side by side? The first form should display as a block level element, while the second form can be inline-block. <form action="#"> <div class="form-group"> <lab ...

The button's color remains static in Internet Explorer despite attempts to change it using a linear gradient background image

I'm curious why the button appears grey in IE and turns blue on hover, rather than starting off blue and becoming darker blue when hovered over. I've managed to make it work in other browsers, but I'm struggling with the code for IE. Thank ...

I specified Authorization Bearer in the Fetch API configuration, however, the Request Headers do not contain the necessary Authorization information

Check out the following code snippet: fetch('http://localhost:3000/tasks/', { method: 'GET', mode: 'no-cors', headers: new Headers({ 'Authorization': 'Bearer <jwt_token>' ...

The command 'npm start' seems to be stuck while trying to start the development server after creating a new react app

As I dive into learning React, my first step is to follow the tutorials and create a React app using 'create-react-app'. However, during the installation process, it brought to my attention some high-severity vulnerabilities which are listed bel ...

React JS - Sending props from Dev and Build to App component

Looking to include static assets and props in my App, specifically having image assets set with a base64 string in the build process. Want to ensure these assets are accessible to the App's props before development and build stages, similar to the fun ...

Challenges encountered when uploading files

Within my react form, I have multiple files that are uploaded to be sent to the backend. Below is a snippet of code for the form submit button: const handleSubmit = async (e) => { e.preventDefault(); setDisabled(true); const ...

Preventing div contents from shrinking with changing screen sizes

I am currently working on creating a portfolio website similar to this one. Check out the Website Here Typically, when the screen size is reduced to less than half of the full width, the content of a website tends to be hidden rather than shrinking. Howe ...

How to Maintain SASS Code Efficiency with Media Queries

How can I avoid repeating myself in my CSS code when using two different media queries for phones and tablets that require the same exact styling? $mobile-portrait: "only screen and (max-width: 680px)"; $tablet-portrait: "only screen and (min-device-wid ...

Invisible boundary line within the column

My task involves creating a table using div elements. The layout of the table includes two columns structured as follows: <div> <div class = "columnborder"><span>Some text for column 1</span></div> <div><span>Some ...

Design your own custom next and previous buttons for material ui pagination

Is there a way to replace the next and prev icons with text "next" and "prev" in material-ui pagination? I have not found any prop for this. Can anyone suggest a workaround? ...

How can I retrieve the background color of the WordPress admin page?

Is there a way in PHP to extract the current active colors of specific elements like #wpadminbar or #adminmenu .wp-submenu from the admin page for my plugin? I am not interested in getting the schema names (base, focus, current)! Here is an example code s ...

Having trouble with NextJs router 404 error when refreshing the page on Digital Ocean?

I am currently working with a NextJs project that has been exported as a static site and is being hosted on Digital Ocean's App platform. I am using next/router to handle routing within the application. One issue that I have encountered is when attem ...

Mouseover feature for image is functioning, but having issues with alignment

I am currently working on displaying images upon mouse over actions. While the functionality is working perfectly, I am facing an issue where the displayed images appear below and the last image takes up space at the bottom. To rectify this problem, I woul ...