Home > Mobile >  Add active class by default to the first element from class list and change active class on click ne
Add active class by default to the first element from class list and change active class on click ne

Time:07-20

I'm a newbie in react. I have two class in css file. One is btn and another is active. I want to set an active class to the first button by default and when I click on other buttons it'll be remove and add to the current button. I'll be thankful if anyone help me about this. Thanks in advance.

Here is my codes

import React, {useState} from 'react';

const Tab = () => {

  const [tabBtn, setTabBtn] = useState(false);

  const handleBtn = () => {
    setTabBtn(true);
  }

  return (
    <div className='btnContainer'>
      <button className={"btn"   (tabBtn ? " active" : "")} onClick={handleBtn}>One</button>
      <button className='btn'>Two</button>
      <button className='btn'>Three</button>
      <button className='btn'>Four</button>
      <button className='btn'>Five</button>
      <button className='btn'>Six</button>
      <button className='btn'>Seven</button>
    </div>
  );
}

export default Tab;

CodePudding user response:

Use this code :

className={`btn ${tabBtn ? " active" : ""}`}

CodePudding user response:

So let's make a few optimizations here: First let's put an array of all your buttons and then use state to track which one is selected.

import React, {useState} from 'react';

const buttonList = ['One', 'Two', 'Three', 'Four'];
const Tab = () => {

  const [tabBtn, setTabBtn] = useState('One');

  return (
    <div className='btnContainer'>
{
  buttonList.map(b => {return (
  <button 
    className={b === tabBtn ? 'active' : '' }
    key={`${b}Button`}
    onClick={() => setTabBtn(b)}
  >
    {b}
  </button>)}
)} 
    </div>
  );
}

export default Tab;

Without map


import React, {useState} from 'react';

const Tab = () => {

  const [tabBtn, setTabBtn] = useState('One');

  return (
    <div className='btnContainer'>

<button 
    className={'One' === tabBtn ? 'active' : '' }
    key={`One Button`}
    onClick={() => setTabBtn('One')}
  >
    One
  </button>
<button 
    className={'Two' === tabBtn ? 'active' : '' }
    key={`Two Button`}
    onClick={() => setTabBtn('Two')}
  >
  Two
  </button>
    </div>
  );
}

export default Tab;

Obviously, add in the rest of the buttons up to 7.

  • Related