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

The same bootstrap column code shows varying behavior

This week, I delved into learning HTML with the goal of creating my own website using bootstrap. However, I encountered a perplexing error - code that should display two pieces of text on the same line is behaving inconsistently for seemingly identical sni ...

The misaligned navigation bar and distortion on mobile devices are causing issues with the website's layout

The logo, search bar, cart, login, and sign up are not aligned on the same line. When I try to view it on mobile, distortion occurs. The search bar and other elements get messed up. In mobile view, nothing happens when clicking on the menu collapse butt ...

What is the best way to target and style anchor links in CSS that are not empty?

Hi there! I am on the hunt for a CSS selector that will target all anchor links that are not empty and contain content. I currently have a selector to identify all links with an anchor attribute, like in this example: a[href*=\#] { background-co ...

What is the best way to manipulate the canvas "camera" in HTML?

I am currently developing a 3D game that involves navigating through skyboxes. My goal is to have the camera respond to user input, specifically detecting key presses (using WASD controls) to move the camera accordingly. Do you have any suggestions on how ...

I'm having trouble with axios.get when trying to search for a product by name

server-side const ProductListFilter = async (req, res) => { try { const productList = await productModel.find(req.query).collation({ locale: "en", strength: 2 }); return res .status(201) .send({ status: true, ...

Tips for refreshing the page using NavLink from React-Router?

Is there a way to use NavLink to highlight buttons with an active link and still load the page like an anchor tag? ...

Determine the Nautical Miles Between Various Coordinate Points using React

Does anyone have a solution for calculating nautical miles using react? Let's say I have this object: const calculateDistance = [ {point_id: 1, long: longitude , lat: latitude}, {point_id: 2, long: longitude , lat: latitude}, {point_id: 3, ...

React Router updates the URL path without actually rendering the content of the second page

I'm having an issue with my React app where the address changes correctly in the search bar, but the page is not loading. Here is my code: import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; i ...

The Heroku API is having trouble retrieving cookies

I am encountering an issue with my JWT auth API hosted on Heroku. When trying to access the API through axios from my front-end React app, I am unable to fetch the protected routes because the required res.cookies are not being set. Interestingly, when tes ...

Material-UI: Creating Radio Button Groups

I have been working on a project using React and Bootstrap. I decided to switch to material-ui, which went smoothly except for the radio buttons. Below is the original code that worked well: <label> <input type={that.props.questionType} name ...

Tone.js is failing to sync sequences during playback

I'm currently working on developing a sequencer using Tone.js. Right now, I have a basic sequence that plays when the user clicks the play button. However, I've encountered an issue where if the button is pressed to pause and then played again, t ...

Steps for connecting a text to the Polyline feature in the React Google Maps API

I am attempting to display the distance attribute on top of the PolyLine with a 45% offset (almost next to the arrow) in this code snippet. Despite my efforts, I have not been able to achieve this successfully. <GoogleMap id="react-google-m ...

Is there an alternative method for categorizing dependencies to determine which ones should be included in the deployment?

I am working on a cross-platform app that will also be deployed on the web using Next.js and Capacitor. Both platforms (web/app) share some assets and codes, with more expected in the future, so I have decided to maintain this system. However, the challeng ...

Does this Docker configuration successfully set up a React.js build to run on port 5000?

Recently, I encountered an issue with my React.js app after dockerizing it. Everything was running smoothly until I updated the node version to 17 and began experiencing errors. To resolve this, I reverted back to using node version 16 in my docker image. ...

React is up and running smoothly on my local machine, but unfortunately encountering issues on Vercel

I have encountered an issue while trying to deploy my website on Vercel. Despite the build logs showing a successful compilation, I am receiving a "failed to compile" error: [16:43:24.951] Running build in Washington, D.C., USA (East) – iad1 [16:43:25.05 ...

The importance of precision in a written text

When it comes to being specific, I usually pride myself on my skills. However, there's one particular challenge that I can't seem to crack. Here's the scenario: Imagine you have a list structured like this: <ul class="dates"> < ...

Steps for retrieving and modifying the state (Object) of a Parent component from a Children component

Within my Parent component, the state is structured like this: const [formData, setFormData] = useState({ firstName: "", middleInitial: "", lastName: "", imageFile: "", extension: "", ...

Begin the NextJS project by redirecting the user to the Auth0 page without delay

I am new to coding and currently working on a project using Typescript/NextJS with Auth0 integration. The current setup navigates users to a page with a login button that redirects them to the Auth0 authentication page. However, this extra step is unneces ...

Cannot display value in NumericFormat when using MUI TextField due to prefix restrictions

When using MUI TextField with the NumericFormat and prefix prop, there seems to be an issue. If I start typing a number quickly, only one digit gets registered. On the other hand, if I type slowly all my numbers show up but the prefix disappears. All inp ...

Leveraging the :has pseudo-class in Tailwind along with adjacent sibling selectors

My CSS code is working perfectly as intended. [data-type='transfer']:has(+ [data-type^='sale_']) { opacity: 0.25; } This CSS snippet targets elements with data-type="transfer" that are next to elements containing data attri ...