paul.kim1901
paul.kim1901

Reputation: 461

Setting "active" className for the menu user selected in React

enter image description here

Just like the screenshot above, I am using Semantic-UI where the selected menu gets highlighted. As my code below, I've set state to whichever menu the user clicks on. My code below works fine, but I think this is inefficient ways to write code since I am basically calling two functions everytime I render just to change the switch out the class names.

Would there be any better way to achieve this?

Please advise.


const Navigation = () => {
  const [selected, setSelected] = useState("Comments");

  const onSelection = (e) => {
    setSelected(e.target.textContent);
  };

  const commentActive = () => {
    return selected === "Comments" ? "active" : "";
  };

  const searchActive = () => {
    return selected === "Search" ? "active" : "";
  };

  return (
    <div className="ui secondary pointing menu">
      <a className={`item ${commentActive()}`} onClick={(e) => onSelection(e)}>
        Comments
      </a>
      <a className={`item ${searchActive()}`} onClick={(e) => onSelection(e)}>
        Search
      </a>
    </div>
  );
};

Upvotes: 0

Views: 515

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53934

I think you shouldn't hardcode the boolean conditions selected === 'Comments' as its bug prone, because if you decide to change the anchor's context without changing the condition you may have a bug: target.textContent !== 'Comments';

Instead use enums:

const NAV_SECTIONS = {
  COMMENTS: "comments",
  SEARCH: "search",
};

const Navigation = () => {
  const [selected, setSelected] = useState(NAV_SECTIONS.COMMENTS);

  return (
    <div className="ui secondary pointing menu">
      <a
        className={`item ${selected === NAV_SECTIONS.COMMENTS ? "active" : ""}`}
        onClick={() => setSelect(NAV_SECTIONS.COMMENTS)}
      >
        {/* We changed the content and the code didn't break */}
        My Cool Comments
      </a>
      <a
        className={`item ${selected === NAV_SECTIONS.SEARCH ? "active" : ""}`}
        onClick={() => setSelect(NAV_SECTIONS.SEARCH)}
      >
        My Best Search
      </a>
    </div>
  );
};

Upvotes: 1

Related Questions