Unable to conceal a DIV using React

I'm attempting to hide a div programmatically upon clicking a button. I've written the following code, but it doesn't seem to be working (the Div remains visible):

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 message and confirmed that the correct display value is being set, but there seems to be an issue when applying it to the div's style.

What am I overlooking here?

Answer №1

Give this method a try:

function CustomButton() {
  const [displaySetting, setDisplaySetting] = useState("visible");

  const toggleDiv = () => {
    setDisplaySetting(displaySetting === "hidden" ? "visible" : "hidden");
  };

  return (
    <>
      {displaySetting === "visible" && <div>MY CUSTOM DIV</div>}
      <button className="custom-btn" onClick={toggleDiv}>
        Click me!
      </button>
    </>
  );
}

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

Answer №2

In accordance with @dai's advice, it is recommended not to directly manipulate the DOM within React (as it operates on a virtual representation of the DOM).

Consider utilizing states instead, like this:

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 intend to include is another component, it is advisable to use contexts instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust iFrame to allow scrolling dynamically

I am currently facing a challenge with creating a non-scrollable iframe element using JavaScript. The function I need to call is within an iframe, and while it works on Firefox and Chrome, I also need it to work on Internet Explorer. My solution involves ...

When inline elements are positioned right next to block elements

Can inline and block elements be placed on the same level without wrapping in HTML? Does it matter if they are wrapped or not? For example: <div class="name"> <span class="name__text">List name</span> </div> <div class="li ...

An error is thrown when trying to use an imported function from Next.js in the getServerSideProps function, resulting in a 'Reference

In my project, I am utilizing Firebase for authentication. Once the user successfully authenticates, I store their id token in cookies. This allows me to validate the token server-side for Server-Side Rendering (SSR) whenever any request is made to a page ...

Is it recommended to use Formik alongside the antd4 Form Component?

It seems that Formik and antd Form both offer similar functionalities: 1. validation 2. data-binding 3. error messages Find more information about Formik here Explore antd Form's features here Are their functions identical? ...

Creating a dual style name within a single component using Styled Components

Need assistance with implementing this code using styled components or CSS for transitions. The code from style.css: .slide { opacity: 0; transition-duration: 1s ease; } .slide.active { opacity: 1; transition-duration: 1s; transform: scale(1.08 ...

Utilize Material-UI's <Autocomplete /> feature to conduct searches using multiple parameters

Recently, I started delving into mastering Material UI and something has been on my mind. We are working with an array of objects as follows: const top100Films = [ { label: 'The Shawshank Redemption', year: 1994 }, { label: 'The Godfath ...

Ways to obtain the file path of the compiled worker.js loaded from the worker loader, along with its hash

Currently, I am working on a TypeScript React application that utilizes Babel and Webpack for compilation. I have implemented a rule to load my worker with the following configuration: config.module.rules.unshift({ test: /gif\.worker\.js$/, ...

What are some ways to personalize the depth graph in amcharts?

I am having trouble modifying the depth graph amchart and I'm struggling to grasp how it functions and how to design it like the image below. Below is the link to the original graph that I am trying to customize: Link https://i.stack.imgur.com/nbWd ...

The issue of anchor links (#) not functioning properly when navigating within the same page of a Next.JS app router

I've encountered an issue with the <Link/> component in my Next.js app. I've set the href to #targetDiv, expecting the page to scroll to the corresponding section with the id #targetDiv upon clicking. However, this functionality is not work ...

Implementing the rotation of an element using 'Transform: rotate' upon loading a webpage with the help of Jquery, Javascript, and

A div element designed to showcase a speedometer; <div class="outer"> <div class="needle" ></div> </div> The speedometer animates smoothly on hover; .outer:hover .needle { transform: rotate(313deg); transform-origin: ce ...

Including a personalized User-Agent string in my headers for fetch requests

Currently, I am utilizing the fetch API within my React project to retrieve data from a JSON endpoint. One requirement I have is to include a custom User-Agent string in my requests. Upon inspecting my requests, I noticed that the UA string displays as: ...

Impact of designs on the elements within components

Here's a CSS query I have: If I have the code below, does the styling apply to the contents of v-container but not v-container itself? <v-app id="inspire"> <v-container justify-center style="max-width: 1200px"> <v-layout row ...

Switching the active className in React and Next.js based on selection status

My goal is to dynamically change the className of each Card component when clicked on. When one Card is selected, the others should revert back to their default className. This is my UserBookingData component: const UserBookingData = ({ bookings }: any) = ...

How can I use CSS to transform a "+" symbol to an "x"?

When I created an accordion using HTML, JS, and CSS, I encountered a problem. The "+" sign in the accordion does not rotate correctly as it should. Instead of rotating from the middle of the "+" sign, it rotates from the top. This is my HTML code: <di ...

Encountering 503 errors with Heroku while making asynchronous API calls in my React application

Almost at the finish line with my project! The coding part was a breeze, but deployment is proving to be quite the nightmare. I've managed to get most of it deployed, but now the app is experiencing timeouts on API calls, even though they work perfect ...

Implement lazy loading for scripts in Next JS

Currently working on a project with Next JS and focusing on optimizations through Google's Page Speed Insights tool. One major performance issue identified is the presence of 3rd party scripts, specifically the Google Tag script (which includes Google ...

Why won't my sticky element function properly with the position attribute set to sticky?

Hey there! I've been diving into learning all about CSS positions and have nailed down most of them. However, for some reason, the sticky position just won't cooperate and is stubbornly acting like a relative one instead. Check out my HTML snipp ...

Interfacing ReactJS with Webview on Native Android platform (undefined variable 'Android' no-undef)

I have developed a web part using ReactJS (not React Native - very important). Additionally, I have a basic Android application with a WebView component, which loads a website running on ReactJS. Is there a recommended approach to establish communication b ...

Concealing and wrapping text using CSS in a table structure

My table is displayed below: <table style="width: 100%; white-space: nowrap; overflow: hidden;"> <tbody><tr> <th> Department </th> <th> Function </th> ...

How can I get rid of the underline in a Material-UI select component?

Is there a way to remove the underline from a Material UI Select list when hovering over it? I attempted using this solution, which successfully removes the underline by default. However, even with this fix, the underline still appears when hovered over. ...