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
Vue.Js Refs Are Undefined, Even Though This.$Refs Shows Theyre There
Starting the Week on Monday With Isoweekday()
Create Clone of Table Row and Append to Table in JavaScript
Map, and Removing Commas from an Array in JavaScript
Regular Expression Which Matches a Pattern, or Is an Empty String
Get Weeks in Month Through JavaScript
Javascript:Change the Function of the Browser'S Back Button
Bootstrap Modal Hide Not Working With Jquery Ajax
Reactjs Redirecting to Another Page
How to Merge the Property With Same Key in Two Object Array
How to I Retrieve Last Part of Url and Use It in HTML
Blob Createobjecturl Download Not Working in Firefox (But Works When Debugging)
Passing Value from Java to JavaScript
Onchange Event Updates State With 1 Character Delay
Filereader Onload With Result and Parameter
Reload Datatable After Ajax Success