Home > Mobile >  React toggle div visibility on button click
React toggle div visibility on button click

Time:01-09

I want to toggle the visibility of the div content on button click. For this, I'm using UseId hook as below

function toggleElement(elm_id) {
  var el = document.getElementById(elm_id).nextElementSibling;
      if (el.style.display === "block") {
        el.style.display = "none";
      } else {
        el.style.display = "block";
      }
   
}
function FAQ(props) {
  const clickedElm = useId();
  return (
    <div className="faq-item">
      <button type="button" id = {clickedElm}  onClick={toggleElement(this.id)} >
        {props.question}
      </button>
      <div className="content">
        <p>{props.answer}</p>
      </div>

The above code is showing Error Boundaries not used error. I'm beginner to React. I didn't understand what it is. Where the code is going wrong?

CodePudding user response:

It is discouraged in react to touch the DOM directly like you do here:

 if (el.style.display === "block") {
        el.style.display = "none";
      } else {
        el.style.display = "block";
      }

because react has its own internal representation to determine what to update what not, etc.

Instead react way of doing something like what you want is this:

import React from 'react';
import './style.css';

export default function App() {
  let [show, setShow] = React.useState(false);
  return (
    <div>
      <button
        onClick={() => {
          setShow(!show);
        }}
      >
        Click
      </button>
      {show && <div>Hi</div>}
    </div>
  );
}

CodePudding user response:

I have solved this issue. please check below code :-

    function toggleElement(elm_id) {
        var el = elm_id.currentTarget.nextElementSibling;
            if (el.style.display === "block") {
              el.style.display = "none";
            } else {
              el.style.display = "block";
            }
    }
    function FAQ(props) {
        return (
           <div className="faq-item">
              <button type="button" id='btntest'  onClick={toggleElement}>
                {props.question}
              </button>
              <div className="content">
                 <p>{props.answer}</p>
              </div>
           </div>
        )
    }

There is no need to use UseId hook here and I have just updated some line of your code. Try this out and let me know if it works for you.

  • Related