Blake Bell
Blake Bell

Reputation: 377

How do I set a links parent <li> to active in React?

In jQuery I can set an li to active when clicking a link by using the following:

<script>
$({
    $('.nav-link li a').click(function() {
    $(this).parent().addClass('active').siblings().removeClass('active');
});
</script>
<ul class="nav-link">
<li class="active"><a href="#">First Link</a></li>
<li><a href="#">Second Link</a></li>
<li><a href="#">Third Link</a></li>
</ul>

How would I handle this in react though?

handleClick(e) {
    e.preventDefault();
    //???
}

render() {
    <ul class="nav-link">
    <li class="active"><a href="#" onClick={handleClick}>First Link</a></li>
    <li><a href="#" onClick={handleClick}>Second Link</a></li>
    <li><a href="#" onClick={handleClick}>Third Link</a></li>
    </ul>
}

Upvotes: 0

Views: 109

Answers (2)

Arthur Rubens
Arthur Rubens

Reputation: 4706

Something like this:

styles.css

.active {
  color: red;
}

.inactive {
  color: blue;
}

App.js

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [links, setLinks] = useState([
    {
      url: "#",
      title: "First Link",
      class: "active"
    },
    {
      url: "#",
      title: "Second Link",
      class: "active"
    },
    {
      url: "#",
      title: "Third Link",
      class: "active"
    }
  ]);

  const handleClick = index => {
    links[index].class = "inactive";
    setLinks([...links]);
  };

  return (
    <ul className="nav-link">
      {links.map((link, index) => {
        return (
          <li className={link.class} key={index}>
            <a href={link.url} onClick={() => handleClick(index)}>
              {link.title}
            </a>
          </li>
        );
      })}
    </ul>
  );
}

Upvotes: 1

Raul Vitor
Raul Vitor

Reputation: 44

e.target.parentNode.classList.add('active')

Upvotes: 1

Related Questions