Home > Blockchain >  React on click add class to dynamically generated element to make it active
React on click add class to dynamically generated element to make it active

Time:04-19

I am using a vertical tab in my react application. So it has labels generated using the below code.

function handleTab(e){
        e.target.className= "LabelActive"
    }

    const domain_str = domains.map((elem, index) => 
            <label onClick={e => {handleTab(e)}} className={index == 0 ? "LabelActive":""}>{elem.domain} <img src="images/tab-arrow-right-icon.svg"/> </label>
        )

I am adding the LabelActive class to a label on click. By default, I am adding the active class to the first label so as to make it active on page load. I want to remove the class from all labels other than the clicked one. How can I do that?

CodePudding user response:

Instead of setting className on click, you should set activeTabIndex in state. And use the activeTabIndex to add 'LabelActive' class.

Refer this live demo: https://codesandbox.io/s/eager-gould-2cp7mq

CodePudding user response:

You can use useState to store the selected index

const [selectedIndex, setSelectedIndex] = useState(0)

    const domain_str = domains.map((elem, index) => 
            <label onClick={e => setSelectedIndex(index)} className={selectedIndex === index ? "LabelActive":""}>{elem.domain} <img src="images/tab-arrow-right-icon.svg"/> </label>
        )
  • Related