How to Toggle Class to a Div Element in Reactjs

toggle class div elements in react.js

I think you could achieve this by changing the state from boolean so it can refer to a specific div:

state = { isActive: '' }; 
handleToggle = (btn) => {
this.setState({ isActive: btn });
};

render(){
const isActive = this.state.isActive;

return (
<>
<button onClick={() => this.handleToggle('button1')} className={isActive === 'button1' ? "btn1" : "btn-on1"}>Toggle class1</button>
<div className={isActive === 'button1' ? "box1" : "box-active1"}>11</div>
<br />
<button onClick={() => this.handleToggle('button2')} className={isActive === 'button2' ? "btn2" : "btn-on2"}>Toggle class2</button>
<div className={isActive === 'button2' ? "box2" : "box-active2"}>22</div>
</>
)
}

How to toggle class to a div element in reactjs?

One thing you could is create an variable (or array if you want more classes) and then add then conditionally.

Render(){
Const divClasses =[‘My-Div’, ‘Container’]

Return(
<div className=
{/*condition*\ && divClasses>
//content
</div>
)
}

So the class(es) will be the added based on a condition. Additionally you could add a handler to control the condition.

Toggle class only on one element, react js

Every element must have its seperate expanded value. So we need an array in state.

And here is the code:

import React, { Component } from "react";

class PageContentSupportFaq extends Component {
state = {
items: [
{ id: 1, name: "First", expanded: false },
{ id: 2, name: "Second", expanded: true },
{ id: 3, name: "Third", expanded: false }
]
};

handleToggle = id => {
const updatedItems = this.state.items.map(item => {
if (item.id === id) {
return {
...item,
expanded: !item.expanded
};
} else {
return item;
}
});

this.setState({
items: updatedItems
});
};

render() {
return this.state.items.map(el => (
<div
key={el.id}
onClick={() => this.handleToggle(el.id)}
className={el.expanded ? "active" : "dummy-class"}
>
<p className="mb-0">
<strong>{el.name}</strong>
<span> {el.expanded.toString()}</span>
</p>
</div>
));
}
}

export default PageContentSupportFaq;



Related Topics



Leave a reply



Submit