1
  1. I map through an array of locations
  2. I want to access the key of the component via onClick
  3. This is my console.logconst addTo = (element) => {console.log(element);};
return (
    <>
      {data.map((item) => {

        return (
          <Marker key={Math.random()} position={item.fields.location}>
            <Popup>
              {item.fields.name} <br></br>
               <button
                onClick={() => {
                  addTo(item.fields.name);
                }}
              >Add 
              </button>
            </Popup>
          </Marker>
        );
      })}
    </>
  );
}
Flexxbo
  • 13
  • 1
  • 4
  • What do you mean by `key of the component`? – ksav Jun 01 '20 at 01:59
  • `key` is a special react prop. It won't be accessible as `props.key` in a component even if you passed it as a prop. But if you need it, you can pass it with a different name: `` and access it as `props.myKey` – Ajeet Shah Jun 01 '20 at 03:21

1 Answers1

0

From the React docs:

Keys serve as a hint to React but they don’t get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name:

Therefore you need to either store the key as a variable or pass it as another prop name

return (
    <>
      {data.map((item, index) => {
        const key = index;
        return (
          <Marker key={key} position={item.fields.location}>
            <Popup>
              {item.fields.name} <br></br>
               <button
                onClick={() => {
                  addTo(item.fields.name);
                  console.log(key)
                }}
              >Add 
              </button>
            </Popup>
          </Marker>
        );
      })}
    </>
  );
}

(Also you should consider using another key other than Math.random, as that changes with every render of the component)

If you want to access the element itself, you should consider using an attribute (i.e. data-id={index}) or better yet a ref. This answer explains how to create multiple refs

james
  • 5,006
  • 8
  • 39
  • 64