Manipulate React class names by adding or removing them

Is there a way to toggle a className on click to change the style of a component?

https://i.sstatic.net/z9FoA.png

  • I need to rotate an arrow to the right when it's clicked and hide all components next to it using display: none;.

  • I also require this functionality to work when the mobile breakpoint is reached.

Answer №1

let [isSpin, setSpin] = useState(false);

triggerSpin() {
 setSpin(true)
}

<button className={isSpin ? 'spin-effect' : ''} onClick={triggerSpin} />
{ !isSpin && <Element/>} // element will be hidden once button is clicked

This method is preferred over using display: none on other elements. However, if necessary, you can do this:

 <Element style={{ display: isSpin ? 'none': 'block' }} /> // It assumes default display style of the elements to be 'block'

Answer №2

To implement boolean state and a function to change the state, you can refer to this code snippet.

function App() {
  const [state, setState] = useState(true);

  const rotateHandler = () => {
    setState(() => !state);
  };

  return (
    <div className="App">
      {/* button for changing the state */}
      <button onClick={rotateHandler}>Click to rotate and hide</button>
      {/* icon for rotation */}
      <div>
        <FontAwesomeIcon
          icon={faAngleRight}
          style={{
            transform: state ? "rotate(90deg)" : "rotate(0deg)"
          }}
        />
      </div>
      {/* text to be hidden conditionally */}
      <div style={{ display: state ? " block" : "none" }}>
        <div>This text will be hidden when the state is false</div>
        <div>You can click the button</div>
        <div>to rotate the arrow icon</div>
        <div>and hide this text</div>
      </div>
    </div>
  );
}

You can also add conditions in className rather than inline styles as shown below:

className={state ? "show" : "hide"}

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

Alert: A new body component is being mounted without unmounting the previous one first

I'm currently working on developing a webpage with one layout for the dashboard and another layout for the default Next.js 13. While testing out the dashboard page, I encountered an issue. Whenever I navigate to different sections within the dashboa ...

Unraveling the Enigma of CSS Grid Whitespace

I'm facing an issue while trying to construct a grid of images using CSS Grid. Interestingly, I am encountering mysterious white space around the first two items in the grid. Upon inspecting the images, I am unable to identify any source of this white ...

Reading Properties in VueJS with Firebase

<template> <div id="app"> <h1 id="title"gt;{{ quiz.title }}</h1> <div id="ques" v-for="(question, index) in quiz.questions" :key="question.text"> <div v-show="index = ...

What could be causing the server to receive an empty request.body when making a POST http request with axios?

Currently, I am facing an issue while attempting to send a file (.obj file) through formdata to my node server. It seems that everything is functioning correctly until the controller of the endpoint on the server throws an error indicating that the formdat ...

Animating with React using the animationDelay style does not produce the desired effect

Is there a way to apply an animation to each letter in a word individually when hovering over the word? I want the animation to affect each letter with an increasing delay, rather than all at once. For example, if scaling each letter by 1.1 is the animatio ...

Div element failing to respond to hover effect

I have implemented a hover effect to display an icon overlay and filter on the Instagram feed of a website I am currently working on. Everything looks perfect when I inspect the element and set the state to hover. However, when I test the website and hover ...

WebStorm facing issues with running create-react-app

I am completely lost with what is happening here, my create react app seems to be malfunctioning. The package installation process came to an abrupt halt in the middle. To troubleshoot this issue, I attempted to run npm cache clean --force and then reinst ...

Is it possible for me to override the redirect feature of Google Optimize manually and bypass the need for

I am currently conducting A/B redirect experiments using Google Optimize on a platform built with React and Redux. One challenge I am facing is the need to avoid full page reloads when redirecting to new pages. Instead, I would prefer a manual approach th ...

React useEffect only retrieves the last element of an array object

I am facing an issue where React seems to only save the last element in my array. Even though I have two elements, when mapping over them, only the last element is being placed in the hook each time. React.useEffect(() => { if (bearbeiten) { handleCli ...

Tips for aligning 2 columns perfectly in a 3 column layout

I am facing an issue with a grid section where the grid-template-column is set for 3 columns, but sometimes the content loaded dynamically only fills 2 columns. I am attempting to center the columns when there are only 2. Despite going through the grid CS ...

Sequence of loading unique CSS skin for MediaWiki

Running a MediaWiki site with a personalized skin, I've noticed that the CSS code from my custom skin is being overshadowed by the default MediaWiki CSS. Is there a way to modify the sequence in which the CSS code is loaded? ...

Should a React application perform a complete refresh when a file is reloaded?

Recently, I delved into the world of React and learned about one of its key benefits: updating only the necessary DOM elements. However, as I began building an app from scratch, I encountered a situation where every time I saved the .js file, it resulted ...

Jenkins encountered an issue with the React build process, generating the following error message: "build-js" exited with code

Currently in the process of transferring my local Jenkins to a new EC2 instance and while moving the UI build pipeline, I encountered an error: ERROR: "build-js" exited with 1. This same error occurred on the existing Jenkins server but was res ...

The input '{ data: InvitedUser[]; "": any; }' does not match the expected type 'Element'

I'm currently facing a typescript dilemma that requires some assistance. In my project, I have a parent component that passes an array of results to a child component for mapping and displaying the information. Parent Component: import { Table } fr ...

When placed within a <li> element, the <a> tag will not create a hyperlink to a page, but it will

I have encountered an issue with my anchor links. All of them are working properly except for the one in the second ul with an href="page1". Interestingly, the link shows the correct destination at the bottom left of my screen and works when I right-click ...

Achieve a CSS design similar to the Cinemax logo with angled background ends

Is there a way to customize the angle at which the ends of a background are cut off when using -webkit-transform: rotate(-#deg); and background selectors for tilted text with a background? I'm looking to achieve a design similar to the Cinemax logo. ...

Obtaining the selected value from a material select dropdown in a react application

Struggling to retrieve the value from a select drop-down using onChange event in react, but the function isn't triggering. handleInputChange(event) { alert("testing") event.persist(); this.setState((state) => { state.registerForm[event ...

Is there a way to adjust the color of the checkbox?

After creating a show/hide toggle checkbox for a password input, I ran into an issue with changing the background color when it is checked. Our current code base includes a custom styled checkbox, but it lacks the ng-model needed for this particular featur ...

Add a touch of mystery to a triangle SVG with CSS shadows

Is there a way to apply shadows to SVG images, like a triangle? I've tried using polyfill solutions but they didn't give me the desired effect. Check out this JSFiddle where I showcase what I'm trying to achieve. This is my HTML: <div c ...

Encountering a problem with scrolling the modal to the top

I am currently working on a code snippet that involves scrolling the modal to the top position. The purpose of this is to display form validation messages within the modal popup. Below are the jQuery code snippets that I have attempted: //Click event t ...