9

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>
        );
    }
});
Hassan Shahbaz
  • 596
  • 1
  • 14
  • 38
  • State should propagate down, not up. Perhaps you could handle events in the parent as well and pass that state down as a prop – scrowler Sep 17 '18 at 09:05
  • @Robbie Averill can you explain a bit more or give me example code as i am new to react thanks. – Hassan Shahbaz Sep 17 '18 at 09:08
  • 1
    Lightweight example: https://jsfiddle.net/8en4vdbz/ Ramya's answer sums it up, but assumes you have access to the div in the current component – scrowler Sep 17 '18 at 09:21

6 Answers6

14

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()
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
4

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

Ramya
  • 150
  • 11
3

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>
    );
}
});
Hema Ramasamy
  • 686
  • 1
  • 6
  • 16
2

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

}

1

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')

gokul-r-16
  • 21
  • 4
0
<div className="myDiv">
    <input type="button"
        onClick={(e)=>e.target.parentNode.classList.add('open')}>
    </input>
</div>