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

6 Answers 6

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()
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

please look this and answer stackoverflow.com/q/58040667/2479903
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>
    );
}
});

Comments

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

}

Comments

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

Comments

0
<div className="myDiv">
    <input type="button"
        onClick={(e)=>e.target.parentNode.classList.add('open')}>
    </input>
</div>

1 Comment

Its best to explain your answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.