Search code examples
reactjsshow-hide

How to "Hide a div by clicking alert box ok button" in reactjs


  1. As I'm new to react I don't know much about hide/show.
  2. In my page, I have toggle button , When I click that button a container appears which contains 3 options.
  3. When I click any one of the options, an alert box appears.
  4. When I click ok button in the alert box, the whole container should hide.
  5. The working demo :codesandboxdemo
  6. The code:

 
.App {
  font-family: sans-serif;
  text-align: center;
}
.style1 {
  cursor: pointer;
  padding-top: 10px;
  border-bottom-left-radius: 1px
}
.style1:hover{
  background-color: #D3D3D3;
}
.box{
  background-color:#eeeeee;
  width:20%;
  margin-top:1px;

}
class Foo extends Component {

  state = { showing: false,  };
  handleClick()
  {
    
       alert("hi");
   
  }

  render() {
      const { showing } = this.state;
      return (
          <div>
              <button onClick={() => this.setState({ showing: !showing })}>toggle</button>
              { showing 
                  ? (
                  <div className="box">
                    <div className="style1" onClick={this.handleClick}>Action1</div>
                  <div className="style1" onClick={this.handleClick}>Action2</div>
                  <div className="style1" onClick={this.handleClick}>Action3</div>
                  </div>
                 )
                  : null
              }
          </div>  
      )
  }
}
export default Foo;


Solution

  • Final output:

    enter image description here

    Here is how you can do that, I am using confirm dialogue box instead of alert as it has an option for OK and Cancel both, so it will be more user friendly:

    import React, { Component } from "react";
    import "./styles.css";
    
    class Foo extends Component {
      state = { showing: false };
      handleClick = () => {
        if (window.confirm("Hide Div Emelent")) {
          this.setState({ showing: false });
        }
      };
    
      render() {
        const { showing } = this.state;
        return (
          <div>
            <button onClick={() => this.setState({ showing: !showing })}>
              toggle
            </button>
            {showing ? (
              <div className="box">
                <div className="style1" onClick={this.handleClick}>
                  Action1
                </div>
                <div className="style1" onClick={this.handleClick}>
                  Action2
                </div>
                <div className="style1" onClick={this.handleClick}>
                  Action3
                </div>
              </div>
            ) : null}
          </div>
        );
      }
    }
    export default Foo;
    

    Working Example: Codesandbox