Home > Enterprise >  Can't hide a DIV with React
Can't hide a DIV with React

Time:11-26

I am trying to programatically hide a div when a button is clicked. Therefore I have written the following code, but it is not working (Div is still there):

import React, {useState} from 'react';
import './Button.css';

export function Button() {
    const [click, setClick] = useState(false);

    const hideDiv = () => {
        var display = 'block';
    
        if (click){
            display = 'none';
            setClick(false);
        }else{
            display = 'block';
            setClick(true);
        }
    
        return ([
            document.getElementById('main').style.display = {display}
        ])
    };

    return(
        <button className='btn' onClick={() => setClick(true), hideDiv}>Some button!</button>
    );
};

I "debugged" the application with an alert and the correct display is coming, but it seems that I am missing something when applying it to the div style.

What am I missing here?

CodePudding user response:

Try this approach,

export function Button() {
  const [display, setDisplay] = useState("block");

  const hideDiv = () => {
    setDisplay(display === "none" ? "block" : "none");
  };

  return (
    <>
      {display === "block" && <div>MY DIV</div>}
      <button className="btn" onClick={hideDiv}>
        Some button!
      </button>
    </>
  );
}

CODESANDBOX - https://codesandbox.io/s/wizardly-water-kf0md?file=/src/App.js

CodePudding user response:

As @dai commented, you shouldn't interact directly with the DOM inside React (because it actually renders a virtual one).

Try using states instead, for example:

import React, {useState} from 'react';
import './Button.css';

export function Button() {
    const [display, setDisplay] = useState(true);

    const hideDiv = () => {
        setDisplay(!display);
     };

    return (
      <>
        {display && (<div id='main'></div>)}
        <button className='btn' onClick={hideDiv}>Some button!</button>
      <>
    );
};

If the div you want to add is an other component, you should use contexts instead.

  • Related