Yumin Lee
Yumin Lee

Reputation: 23

How can I change the style of specific components returned from map function?

I'm new to React and I'm trying to make this part where if a user clicks one of these buttons, that specific button's border color changes to purple. And if another button is clicked, that button's border turns into purple and all the other buttons (including the one clicked previously) borders should contain the original grayish color.

The best I could do was to make an onClick function that changes the border color. So right now, every button I click turns purple. I'm stuck here and I really can't figure out how to make the function work as I want it to.

This is my code and a captured image of how it's working right now.

const UserList = ({ data, index }) => {
  const [isClicked, setIsClicked] = useState(false);
  const onClicked = e => {
    setIsClicked(!isClicked);
  };
  return (
    <UserDiv
      key={index}
      style={{ border: isClicked && color.click }}
      onClick={onClicked}
    >
      <b>{data.name}</b> <br />
      <InfoText>
        {data.company} / {data.position}
      </InfoText>
    </UserDiv>
  );
};

// ...

{TestData.map((data, index) => (
  <UserList data={data} index={index} key={index} />
))}

image capture

Upvotes: 2

Views: 873

Answers (1)

Nokwiw
Nokwiw

Reputation: 396

Can you try this code and tell me if it's work or not :

const UserList = ({ data, index, indexBtnClicked, onClick }) => {
  return (
    <UserDiv
      key={index}
      style={{ border: index === indexBtnClicked && color.click }}
      onClick={()=> onClick(index)}
    >
      <b>{data.name}</b> <br />
      <InfoText>
        {data.company} / {data.position}
      </InfoText>
    </UserDiv>
  );
};

// ...


  const [indexBtnClicked, setIndexBtnClicked] = useState();
  const handleClick = index => setIndexBtnClicked(index);

{TestData.map((data, index) => (
  <UserList data={data} index={index}  onClick={handleClick} indexBtnClicked={indexBtnClicked} />
))}

Upvotes: 1

Related Questions