how to change the text color separately among same styled component tags name?

Viewed 220

I am using React.js and Styled Components. I would like to change the text color only that I clicked among the same components tags.
This is what I did, but I think there is the easiest way to do it. please give me some advice.

import styled from "styled-components";
function Nav() {
    let [picked, setPicked] = useState(new Array(3).fill("black"));

  const handleA= () => {
      setPicked(["orange", "black", "black"]);

  };

  const handleB = () => {
      setPicked(["black", "black", "orange"]);

  };

  const handleC = () => {
      setPicked(["black", "black", "black"]);
  };

  return (
    <Container>
     <List onClick={handleA} style={{ color: picked[0] }}> A </List>
    <List onClick={handleB} style={{ color: picked[1] }}> B </List>
    <List onClick={handleC} style={{ color: picked[2] }}> C </List>
    </Container>
  );
}

const List = styled.li`
  list-style-type: none;
  display: inline;
  padding: 0px 10px 0px 10px;
  border-left: 1px solid black;
  cursor: pointer;
  outline: 0 none;
1 Answers

I would suggest the following, reduce the onClick functions to one function that set the state to the id of the clicked list.

Then, for each List we check if the state pickedList which holds a list id equals that of the current rendered List and we pass this boolean $chechked as a prop to List. If it's true choose 'orange', it it's false choose 'black'.

import styled from "styled-components";
function Nav() {
  const [pickedList, setPickedList] = useState(null);

  const listClickHandler = (listId) => {
      setPickedList(listId);
  };

  return (
    <Container>
    <List onClick={() => listClickHandler(0)} $clicked={pickedList === 0}> A </List>
    <List onClick={() => listClickHandler(1)} $clicked={pickedList === 1}> B </List>
    <List onClick={() => listClickHandler(2)} $clicked={pickedList === 2}> C </List>
    </Container>
  );
}

const List = styled.li`
  list-style-type: none;
  display: inline;
  padding: 0px 10px 0px 10px;
  border-left: 1px solid black;
  cursor: pointer;
  outline: 0 none;
  color: ${({$clicked}) => $clicked ? 'orange' : 'black'};
  `
Related