I want to add/remove class from parent DOM element while click on add/remove button like if i click on add class button then it add new class name "clicked" to parent div and remove that class when click on remove class button:
index.html
<div class="main-div">
<div class="second-div" id="config">
</div>
</div>
config.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import Main from 'Main';
ReactDOM.render(
<Main/>,
document.getElementById('config')
);
Main.jsx
import ReactDOM from 'react-dom'
import React from "react";
import createReactClass from "create-react-class";
export default createReactClass({
getInitialState() {
return {
show-main-div: false
};
},
addClass() {
// want to add new class on parent DOM element i.e <div class="main-div">
},
render: function () {
return (
<div>
<button className="add-class" onClick={() => {this.addClass()}}>
Add Class
</button>
<button className="remove-class" onClick={() => {this.removeClass()}}>
Remove Class
</button>
</div>
);
}
});
You can use the classList. add OR classList. remove method to add/remove a class from a element.
Assign a ref and add/remove the required class:
addClass() {
this.divRef.current.classList.add('main-div')
},
removeClass() {
this.divRef.current.classList.remove('main-div')
}
render: function () {
return (
<div ref={this.divRef}>
<button className="add-class" onClick={() => {this.addClass()}}>
Add Class
</button>
<button className="remove-class" onClick={() => {this.removeClass()}}>
Remove Class
</button>
</div>
);
}
// note: you have to create a ref inside the constructor:
this.divRef = React.createRef()
I'd suggest you do the below:
import ReactDOM from 'react-dom'
import React from "react";
import createReactClass from "create-react-class";
export default createReactClass({
getInitialState() {
return {
main_div_class: "some_initial_class"
};
},
addClass() {
// append the class you want to add to this.state.main_div_class
this.setState({main_div_class: new_value_with_added_class})
},
removeClass() {
// remove the class you want to add from this.state.main_div_class
this.setState({main_div_class: new_value_with_removed_class})
}
render: function () {
return (
<div className={this.state.main_div_class}>
<button className="add-class" onClick={() => {this.addClass()}}>
Add Class
</button>
<button className="remove-class" onClick={() => {this.removeClass()}}>
Remove Class
</button>
</div>
);
}
});
I agree with Bhojendra's answer but it is always better to use states than refs. See here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With