How can I unset an active class on each child component while setting it to active for the clicked child

Related searches

I am trying to set an active class on child component B while disabling the active class on child component A when I click on B.

So far I have tried using hooks in the parent class where I unset the active prop on all childs by using setActive(''); followed by setting the class of the current target to link--active by using e.currentTarget.className === 'link--active' ? e.currentTarget.className = '' : e.currentTarget.className = 'link--active';. Sadly all it does at this moment is add the class or remove the class on the clicked child.

Parent:

  const [active, setActive] = useState('');

  const navigate = (e) => {
    setActive('');
    e.currentTarget.className === 'link--active' ? e.currentTarget.className = '' : e.currentTarget.className = 'link--active';
  };

and in the return statement:

{menuItems.map((item, index) => (
  <li key={index} >
    <NavLink target={item} onClick={(e) => navigate(e)} active={active} />
  </li>
))}

Children:

<a href="#"
   onClick={props.onClick} 
   className={props.active}>
   {props.target}
</a>

Edit:

After using the solution from Ori Drori, the active class was set on the clicked NavLink and removed from the rest. Since I wanted the onClick to be the navigate function, all I changed was set the onClick in the parent to navigate and have the navigate function call setActive by using id as param and calling setActive in the navigate function with id as a param again. The classes now look like this:

Parent:

const [active, setActive] = useState(null);

const navigate = (id) => {
  setActive(id);
};

return (
    {menuItems.map((item) => (
      <li key={item.id} >
        <NavLink 
          {...item}
          isActive={active === item.id}
          onClick={navigate} />
      </li>
    ))}
)

Child:

const NavLink = ({id, target, isActive, onClick}) => {
  return (
      <a href="#"
        onClick={useCallback(() => onClick(id), [id, onClick])} 
        className={isActive ? 'active' : ''}>
        {target}
      </a>
  );
}

Pass setActive to the NavLinks. When a NavLink is clicked it sets it's id via setActive. Each item also receives the isActive property, which is true if the active state matches it's id.

const { useCallback, useState } = React

const NavLink = ({ id, target, isActive, onClick }) => (
  <a href="#"
     onClick={useCallback(() => onClick(id), [id])} 
     className={`navLink ${isActive ? 'active' : ''}` }>
     {target}
  </a>
)

const Parent = ({ menuItems }) => {
  const [active, setActive] = useState(null);

  return (
    <ul>
      {menuItems.map((item) => (
        <li key={item.id} >
          <NavLink 
            {...item} 
            onClick={setActive} 
            isActive={active === item.id} />
        </li>
      ))}
    </ul>
  )
}

const items = [{ id: 0, target: 'Ready' }, { id: 1, target: 'Player' }, { id: 2, target: 'One' }]

ReactDOM.render(
  <Parent menuItems={items} />,
  demo
)
.navLink {
  color: blue;
  text-decoration: none;
}

.active {
  color: red;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="demo"></div>

javascript - Toggle active class on child components, search"; export default class Searches extends React. Could Have: AngularJS </div> <div className="col-xs-2"> <button type="button" onClick={this. When a child element calls this function to set itself as active all of them will fire� AS I understand you need to be able to choise single option in each section. Use only one active class and Setting “checked” for a checkbox with jQuery

(1) Assign an id to each of child components (2)Add inactive class to all child components(3) Remove inactive class from selected component and add active class to it. This is the working solution for your question. I hope it helps.

class App extends React.Component {
  state = {
    childComponents: [
      { id: "ironman", component: <IronMan /> },
      { id: "captainamerica", component: <CaptainAmerica /> },
      { id: "thor", component: <Thor /> },
      { id: "loki", component: <Loki /> },
      { id: "spiderman", component: <Spiderman /> }
    ],
    currComponentId: ""
  };

  clickHandler = idComponent => {
    // get access to all classes
    if (this.state.currComponentId !== "")
      document
        .getElementById(this.state.currComponentId)
        .classList.remove("active");
    let element = document.getElementsByClassName("child-components");
    for (let index = 0; index < element.length; index++) {
      element[index].classList.add("inactive");
    }
    document.getElementById(idComponent).classList.remove("inactive");
    document.getElementById(idComponent).classList.add("active");
    this.setState({ currComponentId: idComponent });
  };
  render() {
    return (
      <div className="parent">
        <ul>
          {this.state.childComponents.map(element => {
            return (
              <li>
                <button
                  id={element.id}
                  className="child-components"
                  onClick={() => this.clickHandler(element.id)}
                >
                  {element.id}
                </button>
                {this.state.currComponentId === element.id ? (
                  <span> Active component</span>
                ) : null}
              </li>
            );
          })}
        </ul>
        <div>
          {this.state.childComponents.map(element => {
            if (element.id === this.state.currComponentId)
              return <div>{element.component}</div>;
          })}
        </div>
      </div>
    );
  }
}


const IronMan = () => <div>This is IronMan Component</div>;
const CaptainAmerica = () => <div>This is CaptainAmerica Component</div>;
const Thor = () => <div>This is Thor Component</div>;
const Loki = () => <div>This is Loki Component</div>;
const Spiderman = () => <div>This is Spiderman Component</div>;

ReactDOM.render(<App/>, document.getElementById('root'));
.active {
  border: solid 1px red;
  background-color: black;
  color: #fff;
}
.inactive {
  color: #000;
  background-color: #fff;
}
.parent{
 border: solid 1px #322f31;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root' />

How to add active class on click event in custom list group in , Recommended Posts: How to remove active nav-tab when click outside of nav- tab in Bootstrap ? How to Set navbar active class with Bootstrap� A link becomes active when you click on it. Tip: The :active selector can be used on all elements, not only links. Tip: Use the :link selector to style links to unvisited pages, the :visited selector to style links to visited pages, and the :hover selector to style links when you mouse over them.

I think I would have a state entry in the parent like whichIsActive, and give it a set property of the active link with the onclick function, like the index for example.

const navigate = (index) => {
this.setState{(whichIsActive: index)}
 };

Then in your className you can do something like className=${this.state.whichIsActive === index && 'active'} (without forgetting the ` around). I have not tested it, but I think it should work.

:last-child Selector, While .last() matches only a single element, :last-child can match more than one: one for each parent. Example: Find the last span in each matched div and add� [#1896674] Added some code for setting the 'active' link class. The way this was implemented breaks other modules' logic. For instance, it completely disregards anything done in hook_preprocess_menu_link() to unset the active link and slaps it right back on there. The least we should do is set that logic in hook_preprocess_menu_link() so other implementations can undo whatever Bootstrap did

how add class active for parent when child router link clicked in , how add class active for parent when child router link clicked in angular 5 - angular. to route to any component by clicking second tab so remove the routerLinkActive from it Try to set your code as below: <a routerLinkActive=" demo_class"� The component being used inside another component is known as the child component and the enclosing component is known as the parent component. Components can communicate to each other in various

Remove a class name from multiple elements with pure JavaScript , That can be done with a `while` loop or with recursion when using a live HTMLCollection. We want to remove those .active classes when the “ Deactivate” button is clicked. classList.remove('active'): When a class name is removed, the element is removed Settings. Default. Boring. Hello Kitty. External links in new tab� I have got the same problem as @tomkel and @chris13524 mentioned.. I use this in Bootstrap 3, simple and clean:. except no active class added to the button :) just to the tab-pane but the tab-content is updated on each click.

Assign "active" class to navbar item based on current page URL with jQuery - footer.js <!-- your average Bootstrap navbar component, in this case placed in an

Comments
  • Thanks for the response, currently it does work, however the next problem I am running into is the fact that each navlink now calls setActive instead of navigate in which setActive is also called. Is it possible to call navigate which in turn will call setActive?
  • Never mind, I have found the solution, I will post it in the edit