0

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} class="collapsible" 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?

2 Answers 2

3

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

7 Comments

{show && <div>Hi</div>} how does this work?
@PRJ well && returns right hand side when both operands are true, so it returns the div, when show is true
I have modified it as above, but it is not working @Giorgi Moniava
Why it is not working with loop?
|
0

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' class="collapsible" 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.

Comments

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.