Search code examples
reactjsonclickreact-hooksuse-statetextcolor

How can I change the color of the text separately with react hooks?


I want the links to work separately

The colors change together now

This is my code

const ChatHeader = ({ location: { pathname } }) => {
  const [color, setColor] = useState("black");
  const [isBlack, setIsBlack] = useState(true);
  const changeColor = (e) => {
    setIsBlack(!isBlack);
    setColor(isBlack ? "#CCCCCC" : "black");
  };
  return (
    <>
      <ChatTexts>
        <ChatText
          current={pathname === "/chats"}
          style={{ color: color }}
          onClick={changeColor}
        >
          <ChatLinks to="/chats">채팅</ChatLinks>
        </ChatText>
        <OpenChateText
          current={pathname === "/openchats"}
          style={{ color: color }}
          onClick={changeColor}
        >
          <ChatLinks to="/openchats">오픈채팅</ChatLinks>
        </OpenChateText>
      </ChatTexts>
    </>
  );
};

How can ChatText and OpenChateText colors be changed differently?

If I enter the "/chats" link, I would like the "/chats" letter color to be black, and the "/openchats" link letter color to be gray.

Conversely, when you enter the "/openchats" link, I want the "/openchats" link letter color to be black and the "/chats" link letter color to be gray.


Solution

  • You could ditch the state and onClick handlers/callbacks and use the pathname to derive the "active" color directly.

    const ChatHeader = ({ location: { pathname } }) => {
      return (
        <>
          <ChatTexts>
            <ChatText
              current={pathname === "/chats"}
              style={{ color: pathname === "/chats" ? "black" : "#cccccc" }}
            >
              <ChatLinks to="/chats">채팅</ChatLinks>
            </ChatText>
            <OpenChateText
              current={pathname === "/openchats"}
              style={{ color: pathname === "/openchats" ? "black" : "#cccccc" }}
            >
              <ChatLinks to="/openchats">오픈채팅</ChatLinks>
            </OpenChateText>
          </ChatTexts>
        </>
      );
    };
    

    An minor optimization to be more DRY

    const ChatHeader = ({ location: { pathname } }) => {
      const getStyle = (path) => ({
        color: pathname === path ? "black" : "#cccccc",
      });
      return (
        <>
          <ChatTexts>
            <ChatText
              current={pathname === "/chats"}
              style={getStyle("/chats")}
            >
              <ChatLinks to="/chats">채팅</ChatLinks>
            </ChatText>
            <OpenChateText
              current={pathname === "/openchats"}
              style={getStyle("/openchats")}
            >
              <ChatLinks to="/openchats">오픈채팅</ChatLinks>
            </OpenChateText>
          </ChatTexts>
        </>
      );
    };