death stranding
death stranding

Reputation: 115

problems while using array.map for null entry in react

I am trying to map the location array but I am unable to do so. I've tried so many stuff in order to map the null object in the array but failed. what mistake am I doing here? if I use a for loop instead of map function then i can do it but i am stuck with the map thing. ...

import React from "react";
import { List, ListItem } from "@material-ui/core";
import { Map, Marker, Popup, TileLayer } from "react-leaflet";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import "./styles.css";
import Icon from "../src/icon.png";
import shadow from "../src/shadow.png";

export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      location: [
        {
          id: 1,
          machine: 1,
          lat: 51.503,
          lng: -0.091
        },

        null
      ],
      center: [51.505, -0.091],
      zoom: 11,
      marker: null
    };
    this.clickAction = this.clickAction.bind(this);
  }

  Icon = L.icon({
    iconUrl: Icon,
    shadowUrl: shadow,
    iconSize: [38, 50],
    shadowSize: [50, 64],
    iconAnchor: [22, 34], // point of the icon which will correspond to marker's location
    shadowAnchor: [4, 62],
    popupAnchor: [-3, -76] // point from which the popup should open relative to the iconAnchor
  });

  openPopUp(marker, id) {
    if (marker && marker.leafletElement) {
      marker.leafletElement.openPopup(id);
    }
  }

  clickAction(id, lat, lng) {
    this.setState({ marker: id, zoom: 16, center: [lat, lng] });
  }

  render() {
    console.log(this.state);
    return (
      <>
        <Map center={this.state.center} zoom={this.state.zoom}>
          <TileLayer
            attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
          />
          {this.state.location &&
            this.state.location.map(location => {
              return location !== null ? (
                <Marker
                  position={[location?.lat, location?.lng]}
                  icon={this.Icon}
                  ref={this.openPopUp(location?.id)}
                >
                  <Popup> {location?.id} </Popup>
                </Marker>
              ) : null;
            })}
        </Map>

        {
          <List style={{ width: "20%", float: "left" }}>
            {this.state.location &&
              this.state.location.map(({ id, machine, lat, lng }) => {
                return (
                  <ListItem
                    key={id}
                    button
                    onClick={() => {
                      this.clickAction(id, lat, lng);
                    }}
                  >
                    Id {id} <br />
                    machine {machine}
                  </ListItem>
                );
              })}
          </List>
        }
      </>
    );
  }
}

... sample code https://codesandbox.io/s/gallant-star-m42qe?file=/src/App.js:0-2858

Upvotes: 0

Views: 451

Answers (2)

Clarity
Clarity

Reputation: 10873

The issue is in your second map statement where you destructure the location object inside the map, which will result in error for null objects. To fix this, you can filter out the null and other falsy locations before mapping them:

 this.state.location.filter(location => location).map(/* ... */) 

You can also use a Boolean shorthand to achieve that:

this.state.location.filter(Boolean).map(/* ... */) 

Upvotes: 1

Vivek Doshi
Vivek Doshi

Reputation: 58543

You are passing null in array, hence the error :

this.state = {
  location: [
    {
      id: 1,
      machine: 1,
      lat: 51.503,
      lng: -0.091
    },
    null // <---- Remove this
  ],

If you want to keep null, then change this line

this.state.location.map(({ id, machine, lat, lng }) => {

to, filter out all null entries before mapping it :

this.state.location.filter(l => l).map(({ id, machine, lat, lng }) => {

WORKING DEMO :

Edit #SO-filter-null-map

Upvotes: 1

Related Questions