Skip to content

fix(android): accept null for layer, MapView, Camera and source props when unset - #4455

Open
gadcam wants to merge 1 commit into
rnmapbox:mainfrom
gadcam:fix/android-null-layer-mapview-props
Open

gadcam wants to merge 1 commit into
rnmapbox:mainfrom
gadcam:fix/android-null-layer-mapview-props

Conversation

@gadcam

@gadcam gadcam commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Description

Follow-up to #4451 / #4454. On Android, when a prop goes from defined to undefined, Fabric sends null to the @ReactProp setter, and Dynamic.asInt/asDouble/asString/asMap/asArray/asBoolean() throw ClassCastException on null. This crashes the app. This PR makes every reproduced, user-reachable case null-safe.

Methodology

  1. Static scan. A script lists every @ReactProp setter that takes a Dynamic and calls asX() with no isNull / type guard. It follows helpers and flags dead asMap() == null checks. It then cross-checks the JS wrapper to see if the prop can actually reach native as null. On main it found 273 setters, 163 unguarded and 119 that can receive null.
  2. Emulator reproduction per family. For each realistic candidate, a reproducer (below) renders the prop and then unsets it with one tap. A case counts as confirmed with 1 crash before the fix and 1 run with no crash and 0 DynamicFromObject logcat lines after it.
  3. Fix only what crashed. Candidates that didn't crash or aren't realistic were left alone (see below).

Fixed (crash before → OK after)

Component Props Behavior when unset
All layers (codepart template + yarn generate) minZoomLevel, maxZoomLevel back to the style-spec defaults 0 / 24
layerIndex layer stays where it is
style no-op (paint/layout properties already applied are not reset)
MapView projection mercator
zoomEnabled true (Mapbox default)
preferredFramesPerSecond keeps the current cap (no upstream "uncapped" reset)
scaleBarUnits keeps the current units
attributionPosition, logoPosition, scaleBarPosition, compassPosition, compassViewMargins keeps the current position (dead == null checks removed)
compassViewPosition no explicit position
Camera followPadding zero padding
RasterSource tileSize default size (applies when the source is created)
sourceBounds ignored
RasterDemSource tileSize default size
VectorSource hitbox default hitbox (relies on the null-safe RNMBXSource.setHitbox(ReadableMap?) from #4454)
ShapeSource url ignored, the shape prop provides the data

Also removed the unused import com.rnmapbox.rnmbx.v11compat.layer.* from RNMBXLayer.kt. That package is empty, so the import failed to compile as soon as the file was recompiled.

Not changed

  • Did not crash (the JS wrapper never sends null): MapView.styleURL (always defaulted), MarkerView.allowOverlap (destructuring default), CustomLocationProvider.heading, Images.
  • Not realistic to unset: identity/structural props like id, sourceID, existing.

Checklist

  • I've read CONTRIBUTING.md
  • I updated the doc/other generated code with running yarn generate in the root folder
  • I have tested the new feature on /example app.
    • In V11 mode/ios
    • In New Architecture mode/ios (Android-only change)
    • In New Architecture mode/android
  • I added/updated a sample - if a new feature was implemented (/example)
Component to reproduce (BugReportExample.js): each button unsets one prop
import React, { useState } from 'react';
import { Pressable, Text, View } from 'react-native';
import {
  Camera,
  CircleLayer,
  CustomLocationProvider,
  Images,
  MapView,
  MarkerView,
  RasterDemSource,
  RasterLayer,
  RasterSource,
  ShapeSource,
  VectorSource,
} from '@rnmapbox/maps';

const center = [-74.00597, 40.71427];
const shape = {
  type: 'FeatureCollection',
  features: [
    { type: 'Feature', properties: {}, geometry: { type: 'Point', coordinates: center } },
  ],
};

// Each case: [component, props passed while "set"]. Unsetting removes them.
const CASES = {
  layerMinZoom: ['layer', { minZoomLevel: 1 }],
  layerMaxZoom: ['layer', { maxZoomLevel: 20 }],
  layerIndex: ['layer', { layerIndex: 1 }],
  layerStyle: ['layer', { style: { circleColor: 'red', circleRadius: 8 } }],
  projection: ['map', { projection: 'globe' }],
  styleURL: ['map', { styleURL: 'mapbox://styles/mapbox/light-v11' }],
  fps: ['map', { preferredFramesPerSecond: 30 }],
  zoomEnabled: ['map', { zoomEnabled: false }],
  attributionPosition: ['map', { attributionPosition: { bottom: 8, left: 8 } }],
  logoPosition: ['map', { logoPosition: { bottom: 8, right: 8 } }],
  scaleBarPosition: ['map', { scaleBarPosition: { top: 8, left: 8 } }],
  scaleBarUnits: ['map', { scaleBarUnits: 'imperial' }],
  compassPosition: ['map', { compassPosition: { top: 8, right: 8 } }],
  compassViewPosition: ['map', { compassViewPosition: 1 }],
  compassViewMargins: ['map', { compassViewMargins: { x: 10, y: 10 } }],
  markerAllowOverlap: ['marker', { allowOverlap: true }],
  followPadding: ['camera', { followPadding: { paddingTop: 10 } }],
  rasterTileSize: ['raster', { tileSize: 256 }],
  rasterBounds: ['raster', { sourceBounds: [-180, -85, 180, 85] }],
  demTileSize: ['dem', { tileSize: 512 }],
  vectorHitbox: ['vector', { hitbox: { width: 10, height: 10 } }],
  shapeUrl: ['shape', { url: 'https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson' }],
  providerHeading: ['provider', { heading: 90 }],
  images: ['images', { images: { pin: require('../assets/example.png') } }],
};

const BugReportExample = () => {
  const [unset, setUnset] = useState({});
  const [log, setLog] = useState('');
  const p = (target) =>
    Object.entries(CASES).reduce(
      (acc, [k, [t, props]]) => (t === target && !unset[k] ? { ...acc, ...props } : acc),
      {},
    );
  const shapeProps = p('shape');
  return (
    <View style={{ flex: 1 }}>
      <View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
        {Object.keys(CASES).map((k) => (
          <Pressable
            key={k}
            style={{ margin: 2, padding: 4, backgroundColor: '#ddd' }}
            onPress={() => {
              setUnset({ ...unset, [k]: !unset[k] });
              setLog(`${log} ${k}`);
            }}
          >
            <Text style={{ fontSize: 11 }}>{`${unset[k] ? 'Set' : 'Unset'} ${k}`}</Text>
          </Pressable>
        ))}
      </View>
      <Text>toggled:{log}</Text>
      <MapView style={{ flex: 1 }} compassEnabled {...p('map')}>
        <Camera centerCoordinate={center} zoomLevel={14} {...p('camera')} />
        <CustomLocationProvider coordinate={center} {...p('provider')} />
        <Images {...p('images')} />
        <ShapeSource id="shape" shape={shape}>
          <CircleLayer id="circles" {...p('layer')} />
        </ShapeSource>
        <ShapeSource id="shape-url" {...(shapeProps.url ? shapeProps : { shape })} />
        <VectorSource id="vector" url="mapbox://mapbox.mapbox-streets-v8" onPress={() => {}} {...p('vector')} />
        <RasterSource
          id="raster"
          tileUrlTemplates={['https://tile.openstreetmap.org/{z}/{x}/{y}.png']}
          {...p('raster')}
        >
          <RasterLayer id="raster-layer" style={{ rasterOpacity: 0.2 }} />
        </RasterSource>
        <RasterDemSource id="dem" url="mapbox://mapbox.mapbox-terrain-dem-v1" {...p('dem')} />
        <MarkerView coordinate={center} {...p('marker')}>
          <View style={{ width: 10, height: 10, backgroundColor: 'blue' }} />
        </MarkerView>
      </MapView>
    </View>
  );
};

export default BugReportExample;

🤖 Generated with Claude Code

… when unset

Unsetting these props makes Fabric send null, which crashed in
DynamicFromObject.asX(). Each setter now treats null as unset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@gadcam
gadcam force-pushed the fix/android-null-layer-mapview-props branch from 82f3f15 to a4737a0 Compare November 23, 2026 18:47

This branch was previously deployed

1 inactive (outdated) deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant