Customize your click event with conditional styling in React

When the onClick event is triggered, I am attempting to modify a class by calling my function. It appears that the function is successfully executed, however, the class does not update in the render output. Below is the code snippet:

import React from 'react';

const Something = props => {
  let opened = false;

  const toggle = () => {
    opened = !opened;
  };

  return (
    <div className={opened ? 'some-class opened' : 'some-class'}>
      <div className="some-inner-class" onClick={toggle}>
       ...content
      </div>
    </div>
  );
};

export default Something;

My goal is to adjust the style when the click event occurs.

Answer №1

If you're looking for a solution in this situation, I recommend implementing react hooks. Take a look at this updated code with my suggestion included: I hope this proves to be helpful.

import React, { useState }  from 'react';

const Something = props => {
  // ***since variables cannot persist between function calls in a function component, using a react hook like useState would be the ideal approach to maintain the value of opened.
  
  const [opened, setOpened] = useState(false);

  return (
    <div className={opened ? 'some-class opened' : 'some-class'}>
      <div className="some-inner-class" onClick={() => setOpened(true)}>
        <p>Click me</p>
      </div>
    </div>
  );
};

export default Something;

Answer №2

To trigger a rerender in React, you must update the state accordingly. A typical way to create and initialize state is by using a constructor:

constructor() {
  super();
  this.state = { isOpen: false };
}

In your toggle function, make sure to call

this.setState({ isOpen: !this.state.isOpen });

Currently, your component seems to be a stateless functional component. To address this, consider either turning it into a class that extends React.Component, or explore using hooks as outlined in https://reactjs.org/docs/hooks-state.html. Since you seem new to working with React, I recommend starting with converting the component into a class, then gradually transitioning to hooks for better practice.

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

Transforming Lapton images into JPEG format on the fly

I have been working on a project where I am compressing jpeg images to .lep format. Now, I have created an .exe file that can convert the .lep image back to jpeg. My goal is to write a simple JSP script that can decode the .lep image on-the-fly and displ ...

Can a tooltip be integrated into the Material UI chip component?

I need to display a label, such as "Color," and its corresponding value, like "orange." I would like to show the label as a tooltip and the value as a chip. Is it possible to achieve this using a chip component? If not, are there any alternative methods fo ...

The behavior of React refs varies between development and production environments when using Next.js

Currently, I'm following a tutorial which can be found here (Update: I have created a GitHub project to demonstrate the issue here, with different behaviors when running in dev or prod modes) (Update 2: A sandbox project has been set up to showcase ...

NextJS getStaticProps failing to pass fetched data to the page component

Struggling with passing props from getStaticProps function into template pages in NextJS. Below is the code for the dynamic page template that I am using. // src/pages/blog/[slug].js import React from 'react'; import matter from 'gray-matte ...

React: Unable to locate an index signature with a parameter of type 'string' on type N

While working with a React component, I encountered an issue when trying to access a property from my component state using a key. My editor showed the following warning: Element implicitly has an 'any' type because expression of type 'str ...

Using CSS styles in emails can lead to an unexpected horizontal scrolling effect

I am currently working on an application using Symfony, and I have implemented a basic confirmation email with minimal CSS styling. However, the email template is causing horizontal scrolling due to the layout. Below is the HTML code of my email template: ...

Comparing the syntax of JSON to the switch statement in JavaScript

I recently came across a fascinating post on discussing an innovative approach to utilizing switch statements in JavaScript. Below, I've included a code snippet that demonstrates this alternative method. However, I'm puzzled as to why the alter ...

Getting a blank request body error while receiving data from an Angular 4 application in Express

My express route is indicating that the body of the request being sent is empty, according to req.body. The main node file looks like this - var express = require('express'); var bluebird = require('bluebird') const bodyParser = requ ...

The navigation bar in Bootstrap has unique behavior with links

I am currently in the process of creating a navigation bar using Bootstrap, you can view it here All the links on the navbar are behaving similarly except for the 'Save and exit' link. How can I adjust it to look consistent with the other links? ...

Overflow - conceal the scrollbar and prevent scrolling without cutting off the element

Whenever I implement the code snippet below: body { overflow: hidden; } The overflowing element gets clipped. However, when I try this code instead: body { overflow: auto; } The element is no longer clipped, but now a scrollbar appears where it ...

Patience is key when it comes to waiting for a function to finish before moving on to the next step

I'm delving into the world of node js and currently immersing myself in the concepts of promises and async/await. Here's a code snippet I've been experimenting with, but I can't quite figure out how to ensure that the code waits until t ...

Expanding the table area in bootstrap

I am currently working on a video slider using bootstrap. I have added a table within the slider (carousel) and it is functioning perfectly. However, I am now looking to update the layout to resemble the image below. I have successfully applied the backgro ...

Include a link in the email body without displaying the URL

My concern revolves around displaying a shortened text instead of the full link within an email. When the recipient clicks on "Open Link," they should be redirected to the URL specified. The text "Open Link" must appear in bold. My current development fram ...

Single repository for shared libraries such as ReactJs, Material-UI, and more

Currently, I am delving into the concept of monorepos and envisioning a setup that includes: /apps = applications /components = numerous individual components /shared = main source libraries for ReactJS, Material-UI, etc. The rationale behind this setup i ...

Listening to a song on a webpage while filling out the online form

Seeking advice on integrating audio file selection in form: <form ....> <input type="file" name="file-main" id="file-main" class="inputfile inputfile-3" multiple/> <audio preload="none" src=""> // excluding submission buttons for brevi ...

What is the best way to reset the column filter cell in Material-Table?

Within my Material-Table, I am utilizing this unique TextField to craft a specialized filter cell for each column. My goal is to employ the endAdornment as a button that will reset the filter, but I am struggling with removing the current value. filterCom ...

Tips for creating a breakpoint in Sass specifically for a 414px iPhone screen size

For my latest project, I am utilizing sass and looking to incorporate a sass breakpoint or media query. My goal is to have the code execute only if the screen size is 414px or less. Below is my existing code: @include media-breakpoint-down(sm) { .sub-men ...

Positioning an Element on a Web Page in Real-Time

Trying to implement an Emoji picker in my React application, I have two toggle buttons on the page to show the picker. I want it to appear where the Toggle button is clicked - whether at the top or bottom of the page. The challenge is to ensure that the pi ...

What steps do I need to follow in order to properly execute this HTTP request?

Recently, I came across this amazing tool called SimplePush.io that is perfect for one of my projects. It works flawlessly via curl, as shown on their website: ~ $ curl 'https://api.simplepush.io/send/HuxgBB/Wow/So easy' or ~ $ curl --data &ap ...

Ways to identify when a modal window is being closed in the angular-ui $modal component

I am currently utilizing the $modal from angular-ui to generate a modal window. Below is the code snippet for creating the modal: this.show = function (customModalDefaults, customModalOptions, extraScopeVar) { //Create temporary objects to work with s ...