Add/Remove class to parent DOM element React js

Viewed 29492

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>
        );
    }
});
5 Answers

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

you can add and remove the classes to particular div (onClick). If you have to set and remove the state like button, its better to go with setState

addClass(e) {
                e.target.classList.add('yourclass');

}
removeClass(e){
                   e.target.classList.remove('yourclass');

 }

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>
    );
}
});

Writing the above answer but with useRef and setTimeout to add/remove classses based on specific interval

import React,{useRef} from 'react';

export default some fucntion  ... {

Note: You have to first define your useRef.

const node = useRef(""); // this is your initial value of ref

// this is called when the div is clicked
const handingRef = ()=>{ 

   let timeout = null;

  
   // to add class, you can do
    node.current.classList.add("name of the class");
   
    // to remove the class, you can do
    node.current.classList.remove("name of the class");

    // to clear setInterval

    if(timeout){
      clearTimeout(timeout)
      timeout=null;
     }

   // if you want to remove a class after some time

    setTimeout(()=>{
      node.current.classList.remove('Section1-row1-shopClosed')
    
     },time in milli-second)

}

return(){
  <div>
  ...
     <div ref={node} onClick={handingRef}> {content ... } </div>

 </div>
 }

}

You can view the targeted class form BOM elements and remove the class form the classlist like event.target.classList.remove('the class name which you want to remove')

Related