Updating a div's class upon clicking in React

This is my code:

render() {
    return (
      <div  className='btndiv'>
        <button className='btn'>Hide</button>
      </div>
    );
}

I'm trying to change the class of the div from .btndiv to .btndivhidden when the button is clicked, essentially hiding it from the screen.

.btndivhidden{
  display: none
}

I've looked at various solutions but many seem too complex and lengthy. What's the most efficient and concise way to achieve this?

Answer №1

If you're looking for a simple solution, try implementing the following code snippet:

const App = () => {
  const [isVisible, setIsVisible] = React.useState(true);

  const handleClick = () => setIsVisible(false);

  return (
    <div className={isVisible ? 'btndiv' : 'btndivhidden'}>
      <button className='btn' onClick={handleClick}>
        Hide
      </button>
    </div>
  );
}

Answer №2

While this may not be the most optimal approach in handling react, it does get the job done! When I first started using react, I wasn't very familiar with it and would resort to these sort of quick fixes. If you find react overwhelming, give this a try to help yourself get more comfortable.

const hideElement = () => {
  const element = document.querySelector(".btnContainer");
  element.classList.replace("btnContainer", "hideBtnContainer");
};
export default function App() {
  return (
    <div className="App">
      <div className="btnContainer">
        <button className="btnClass" onClick={() => hideElement()}>
          Hide Button
        </button>
      </div>
    </div>
  );
}

Answer №3

import React, { useState } from "react";

export default function ToggleButton() {
  const [isToggled, setIsToggled] = useState(true);

  const handleToggle = () => setIsToggled(!isToggled);

  return (
    <div className={isToggled ? "toggleOn" : "toggleOff"}>
      <button className="toggleBtn" onClick={handleToggle}>
        Toggle
      </button>
    </div>
  );
}

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

An image on the left side of a perfectly aligned text

I am currently working on aligning an image and text for a logo. However, I am having trouble justifying the second line to the width of the block. Here is the desired result: This is what I have tried: @import url(http://fonts.googleapis.com/css?famil ...

Animating a background image to slide in from the bottom to the top using CSS transition

Here is a link to a codepen example: https://codepen.io/jon424/pen/XWzGNLe The current effect in this example involves covering an image with a white square, moving from top to bottom when the "toggle" button is clicked. I am interested in reversing this ...

Tips on customizing the appearance of mat-card-title within a mat-card

Is there a way to truncate the title of a mat card when it overflows? I tried using the following CSS: overflow:hidden text-overflow:ellipsis white-space: nowrap However, the style is being overridden by the default mat-card style. I attempted to use mat ...

Tips for showing the value in the subsequent stage of a multi-step form

Assistance is required for the query below: Is there a way to display the input field value from one step to the next in multistep forms? Similar to how Microsoft login shows the email in the next step as depicted in the image below: ...

Issues with jQuery animate not functioning properly when triggered on scroll position

I found a solution on Stack Overflow at this link, but I'm having trouble implementing it properly. The idea is to make an element change opacity from 0 to 1 when the page is scrolled to it, but it's not working as expected. The element is locat ...

Utilizing environmental variables within React builds: A step-by-step guide

Within my React project, I rely on certain environmental variables that may need to be updated periodically. I've observed that when I run 'npm run build', these environmental paths become hardcoded. For example: const server_address = proce ...

Module '@babel/core' not found

Currently, I'm working through a tutorial on webpack4/react which can be found here: https://www.youtube.com/watch?v=deyxI-6C2u4 I have followed the instructions exactly up until the point where he executes npm start. However, when I try to run it, ...

Exploring the world of child theme customization in WordPress

I am looking to make some modifications to my website. Working with a child theme, I have plans to adjust the CSS and make some structural changes. Modifying the CSS seems pretty straightforward as I just need to reference the classes or IDs and input new ...

Animate all shapes in SVG to rotate around a central pivot point

I am looking for a simple way to make an SVG graphic rotate around its center point. The rotation doesn't need to be smooth, just a 90 degree turn and back every second. Here is the SVG code: <?xml version="1.0" encoding="utf-8"?> <svg vers ...

Having trouble with 'react npm run build' failing, but running 'npm start

My application is consistently failing to create an npm build and is throwing the following error: > react-scripts build Creating an optimized production build... Failed to compile. Cannot read property 'toLowerCase' of undefined Com ...

What is the best way to ensure bootstrap cards' container expands horizontally?

Currently experimenting with Bootstrap 4 cards (view more at ) My goal is to have a container with a card deck inside that stretches horizontally as I add new cards, causing a horizontal scrollbar to appear when needed. By default, when the container wid ...

The wrapper.find function is malfunctioning as a result of a connection issue

There seems to be an issue with the following test case using jest and enzyme: it('Displays Trade component', () => { console.log("Testing Shallow", wrapper) expect(wrapper.find('Trade').length).toEqual(1); }); To debug, ...

Choose different components that possess the X designation

Can X number of elements (h1, p, span...) be modified only if they have a specific class? I'm searching for a solution like this: (elem1, elem2, elem3, elem4).class { /* add customization here */ } I previously attempted using parentheses, curly b ...

Incorporating various elements within a single column of a table

I have been attempting to include multiple table cells elements beneath each of my heading cells, but I am facing issues in getting it to work properly. For better understanding, this is a screenshot: https://i.sstatic.net/kg2XR.png My goal is to have o ...

Utilizing Generic Types in React TypeScript Functional Components

I'm currently developing a TypeScript React component that includes generic type props, so I define the React component as: export interface MyCompProps<T> { items: T[]; labelFunction: (T) => string; iconFunction: (T) => JSX.Element; ...

Eliminating empty space within my container

I am facing an issue with a container that contains an image and a button on top of it. There seems to be some extra space created within the container on the right side which is taking up more space than necessary. The layout consists of three horizontal ...

A guide to storing data externally by utilizing the useReducer() function

While working on an application with a complex data model, I found that useReducer() is a suitable choice. Instead of sharing my original code, I will be referring to the example from React docs and explaining the modifications I intend to make. Consider ...

Module Ionic not found

When I attempt to run the command "ionic info", an error is displayed: [ERROR] Error loading @ionic/react package.json: Error: Cannot find module '@ionic/react/package' Below is the output of my ionic info: C:\Users\MyPC>ionic i ...

Creating a CSS grid layout with an unspecified number of columns all set to equal width

Currently, I am in the process of designing a navigation bar using grids. In essence, when the user is an admin, there should be two additional links at the end of the bar. These links need to have the same width and should not be affected by the amount of ...

Tips for positioning buttons using HTML and CSS

Looking for some help with my HTML page design. I have a few buttons that I want to style like this: https://i.stack.imgur.com/3UArn.png I'm struggling with CSS and can't seem to get them positioned correctly. Currently, they are displaying "bel ...