Search code examples
reactjsnext.jsreact-propsreact-componentreact-leaflet

Accessing key property of React component


  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>
        );
      })}
    </>
  );
}

Solution

  • 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