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?

  • 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

Modify the text or background shade of the Bootstrap date picker

I have successfully integrated the bootstrap date picker (view figure below) and it is functioning as expected. The code appears like this: <div class="input-group date"> <input name="departure" type="text" class="form-control" id="departure" ...

Troubleshooting problems with background-image in CSS using Javascript

My latest project involves coding to assign background images to various classes using jQuery. The image files are named in a numerical order, such as 0bg.jpg, 1bg.jpg, 2bg.jpg, and so on. for (i=0; i < 8; i++) { $('.hpCarousel:eq('+i+' ...

What are the steps to fix a timeout error with React.js and socket.io acknowledgements?

My setup includes a Node.js server and a React.js client application. Data is exchanged between them using socket.io, but I'm running into an issue with implementing acknowledgment. Whenever I try to implement acknowledgment, I receive a timeout error ...

What is the best way to make a hyperlink in HTML open in the same page or window, without relying on the <iframe> tag or JavaScript?

I have two html files and one css file. My question is how to open the link monday.html on the same page or window in my content section. For example, when someone clicks on the Monday navigation button, I want the result to show up in the content section ...

Design an aesthetically pleasing chat interface using CSS styling

Currently, I am working on organizing HTML elements to create a user-friendly interface. Utilizing MVC and ASP.NET for this chat client, I have encountered an issue with correctly arranging the items. The default MVC project in Visual Studio provides a str ...

Altering the placement of a single element from floating to fixed positioning in CSS

Currently in the process of designing a basic website, I am looking to modify the behavior of the navigation bar on the left-hand side. I want it to remain fixed in its position so that users can scroll through the page without losing sight of it. My main ...

When refreshing the token in Apollo GraphQL, the useQuery does not get automatically updated

I'm currently encountering the following issue: I am utilizing a useQuery hook to retrieve userData GET_USER_INFO useQuery const { data:dataGetUserInfo, loading:loadingQuery, error:errorQuery,refetch } = useQuery(GET_USER_INFO, {variables: { ...

What is the process for modifying a task on my to-do list with a long press?

I'm currently working on implementing a task update feature in my project. However, I've encountered an issue where the prompt only works in the browser environment. Is there a way to make this work in React Native or are there any alternative so ...

What is the best way to align an element at the bottom in order to allow it to grow vertically

I have a unique structure on one of my pages that I want to use for a tooltip style behavior. When the "container" element is clicked, the "child" element, which is initially hidden, should appear above the container. However, since the child's height ...

What is the best way to extract a single item from an array in Javascript and assign it to a different variable

I am currently dealing with an array of objects structured like this: contacts: [ { id: 1, name: "John Doe", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="066c696e6846616b676f6a2865696b">[emai ...

Guide to transmitting a "token" to an "API" using "React"

As a novice developer, I am facing a challenge. When users log in to our website, a JWT is created. I need to then pass this token to the API on button click. If the backend call is successful, the API response should be displayed. If not, it should show ...

Unable to reveal hidden text with invisible formatting (font-size: 0)

I have a Joomla 3 website where I created a blog using a design-controll template. I made a "new-article" page but realized that some buttons were missing text. Upon inspecting with Firebug, I found that there was a font-size:0 property causing this issue. ...

The function signature '() => void' cannot be assigned to a variable of type 'string'

Encountering an issue in Typescript where I am attempting to comprehend the declaration of src={close} inside ItemProps{}. The error message received reads: Type '() => void' is not assignable to type 'string'. Regrettably, I am un ...

Ways to connect images located outside of the Next.js project directory

Currently, I am working on a project that utilizes node.js and express for the back-end, as well as next js for the front-end. One of the features of this project is a form where users have the ability to create new products, each accompanied by an image. ...

Leveraging the power of context to fetch data from a store in a React component within the Next

I'm having trouble with the title in my React project, and I'm new to React and Nextjs. When trying to fetch data from my dummy chat messages, I encountered this error: × TypeError: undefined is not iterable (cannot read property Symbol(Sy ...

Tips for Providing Real-Time Data for a Dynamic Chart in d3

I have a line chart sample from D3, and the issue I'm facing is that I need to continuously feed live data from a server at certain time intervals and use D3 to draw the chart based on this dynamic data. Despite my efforts to search for a solution, I ...

When HTML elements are dynamically inserted through JavaScript using quilljs, they may cause conflicts with the layout properties

I am currently working on creating a simple webpage layout similar to that of Stack Overflow, with a sidebar and a main content area that can scroll. In my case, the content area is intended to host a QuillJS text editor. To integrate the QuillJS editor i ...

Ways to generate multiple void components side by side using React

What is the most efficient method for creating multiple empty inline elements using React in a declarative manner? Suppose I need 8 empty divs, I tried the following approach but it didn't work. Is there a more effective way? render() { return ( ...

populating all available space in layouts using bootstrap columns

I am attempting to create a grid layout using bootstrap, but I am facing an issue with positioning one of the columns. I have tried adjusting the placement of the divs and using offsets/pulls, but so far I have not been successful. To explain what I am a ...

Encountered an error trying to access property 'history' of an undefined value while using react-router v4 and create-react-app

I encountered an issue with using Link to navigate, here's the breakdown of my code: Directory structure components ----App.js ----home ----Home index.js index.js import React from 'react'; import ReactDOM from 'react-dom'; ...