Sohaib Furqan
Sohaib Furqan

Reputation: 331

toggling class dynamically in react?

I am working on a React application that has a header component with two buttons:

import React, { useRef } from 'react';
import { Link } from 'react-router-dom';

const Header = () => {
  return (
    <header className='header'>
      <h2 className='resume-title'>
        Muhammad <br />
        Sohaib Furqan
      </h2>
      <button className='btn'>
        <Link to='/'>Home</Link>
      </button>
      <button className='btn'>
        <Link to='/projects'>Projects</Link>
      </button>
    </header>
  );
};

I want to make it so that the button that is clicked gets the 'active' class while the other buttons the 'active' class is removed. In vanillaJS, I would use 'querySelectorAll' to get all buttons and then map through the nodeList, toggling as appropriate. But not sure how I would do that in React. I'm inclined towards useRef but how can I set ref to point to the button that was clicked?

Hope I've managed to make myself clear.

TIA, Sohaib

Upvotes: 0

Views: 562

Answers (3)

sid busa
sid busa

Reputation: 186

import React, { useState } from 'react';
import { Link } from 'react-router-dom';

const Header = () => {
  const [active,setActive] = useState("Home")
  const handleActive = (activeTab) => {
     setActive(activeTab)
  }
  return (
    <header className='header'>
      <h2 className='resume-title'>
        Muhammad <br />
        Sohaib Furqan
      </h2>
      <button className={active === "Home" ? 'btn active' : 'btn' } onClick={() => handleActive("Home")} >
        <Link to='/'>Home</Link>
      </button>
      <button className={active === "Projects" ? 'btn active' : 'btn' } onClick={() => handleActive("Projects")} >
        <Link to='/projects'>Projects</Link>
      </button>
    </header>
  );
};

Upvotes: 1

Ramesh Reddy
Ramesh Reddy

Reputation: 10652

See NavLink.

You can use it like

<NavLink className="btn" to='/'>Home</Link>

NavLink will get .active class when path matches. So you can add styles to the active class.

You can also customize the className using

<NavLink to="/" activeClassName="some-custom-class">
 Home
</NavLink>

Upvotes: 2

Manish Jangir
Manish Jangir

Reputation: 5437

<Link> no longer has the activeClassName or activeStyle properties. In react-router v4 you have to use <NavLink> if you want to do conditional styling:

import React, { useRef } from 'react';
import { NavLink } from 'react-router-dom';

const Header = () => {
  return (
    <header className='header'>
      <h2 className='resume-title'>
        Muhammad <br />
        Sohaib Furqan
      </h2>
      <NavLink to='/' className="btn" activeClassName="active">Home</Link>
      <NavLink to='/projects' className="btn" activeClassName="active">Projects</Link>
    </header>
  );
};

and in your style.css

.active { //do-whatever }

Upvotes: 1

Related Questions