Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading