'button only clicks once, at one div element

this is the onclick function

export function changeColorButton() {
  document.getElementById("friendDiv").style.background = "grey";
}

this is the output file. I want every button to be clickable and give background grey

 {data.projects.map((project, key) => {
    return (
      <div id="friendDiv" className="relative">
        <div key={key} className="flex flex-row items-center space-x-6 mb-6">
          <img src={project.image} />
          <div>
            <h1 key={key} class=" text-xl font-bold">
              {project.name}
            </h1>
          </div>
          <button
            className="absolute right-10 bg-bgButtonAddPeople p-2"
            onClick={changeColorButton}
          >
            Legg til
          </button>
        </div>
      </div>
    );
  });
}


Solution 1:[1]

You would just need to componentize the div element that is being mapped. So you can follow an approach like this.

Each FriendDiv element would have its own instance of changeColorButton, so it would apply the color to its own element.

FriendDiv.js

const FriendDiv = ({ key, project }) => {
  const [isGrey, setIsGrey] = useState(false);

  const changeColorButton = () => {
    setIsGrey(!isGrey);
  };

  return (
    <div
      style={{ backgroundColor: isGrey ? 'grey' : 'default-color}}
      id="friendDiv"
      className="relative"
    >
      <div key={key} className="flex flex-row items-center space-x-6 mb-6">
        <img src={project.image} />
        <div>
          <h1 key={key} class=" text-xl font-bold">
            {project.name}
          </h1>
        </div>
        <button
          className="absolute right-10 bg-bgButtonAddPeople p-2"
          onClick={changeColorButton}
        >
          Legg til
        </button>
      </div>
    </div>
  );
};

App.js

const App = () => {
    return data.projects.map((project, key) => {
        return <FriendDiv project={project} key={key} />;
    });
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1