How to conditionally set the active class in a React component

I am new to using React and I am encountering some issues. My goal is to add an active class when any of these components are opened. I have attempted a solution but it isn't working as expected. I need assistance in adding a background color to the divs with the className 'menu__iconsRight' when they are active. Any help would be greatly appreciated. Thank you.

 const App = () => {

 const[isStyleOpen, setIsStyleOpen]=React.useState(false)
 const[isRectOpen, setIsRectOpen]=React.useState(true)
 const[isHairOpen, setIsHairOpen]=React.useState(false)

    function openHair(){
      setIsHairOpen(true)
    }
    function closeHair(){
      setIsHairOpen(false)
    }

    function openRect(){
     setIsRectOpen(true)
    }
    function closeRect(){
      setIsRectOpen(false)
    }

    function openStyle(){
     setIsStyleOpen(true)
    }
    function closeStyle(){
     setIsStyleOpen(false)
    }


     return (
      
          <div className='menu'>         
            <div className='menu__iconsRight ' >
            <img   onClick={() => setIsRectOpen(!isRectOpen)} 
              src="./images/icons/win.png"/>
              {isRectOpen ? <Rect />: null}
          </div>
       
           
            <div className={`?active: 'menu__iconsRight' `}    >
            <img    onClick={() => setIsStyleOpen((isStyleOpen) => 
             !isStyleOpen)} 
              src="https://winaero.com/blog/wp-content/uploads/2017/07/Co-win-- 
              icon.png"/>
               {isStyleOpen ? <Style  closeStyle={closeStyle}  />: null}
            </div>
       
              <div className='menu__iconsRight '>
                <img    onClick={() => setIsHairOpen(!isHairOpen)} 
              src="./images/icons/at.png"/>
               {isHairOpen ? <Hair closeHair={closeHair}  />: null}   
               </div>
              
          )
       }
     export default App

Answer №1

To achieve your desired result, you can use the following code snippet:

...
<div className={"menu__iconsRight " + ((isRectOpen) ? "active": "")}>
...

Does this code meet your requirements?

Answer №2

To manage intricate scenarios, consider leveraging the classnames library:

<div className={classnames("menu__iconsRight", {
  "active": isRectOpen
})}>

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

Limiting click event to only Image component in Next.js

Is there a way to trigger a click event only on the image itself, rather than the entire parent div? When setting width and height for the parent div, the click event seems to encompass the entire area. For instance, if the image is 600 pixels wide by 300 ...

Guide to receiving dynamic argument variables in jQuery using $.get

I am currently working on developing an Ajax function call. In this function, the argument q will be dynamically defined, and the $.get method will return either true or false based on the data received from the Ajax call. <a href="any.php" class ...

Troubles encountered when attempting to deploy NextJS app on IIS web server

Hey there! I've been given the task of deploying our new web app to an IIS windows server, but I'm facing a problem that I can't seem to solve. The create-next-app I have is very basic with minimal code, and my goal is to deploy it to the s ...

Addressing the issue of pm2 with netmask 1.0.6 posing a serious security risk

While working on my project, I encountered a problem in the terminal when using the pm2-runtime command for the runtime environment. When running the command npm i, I received warnings at two levels: High netmask npm package vulnerable to octa ...

Icon toggling menu bug

I recently designed a menu featuring an animated icon that, when clicked, opens with two columns. The issue I'm facing is that after clicking on a link in the right column (view JSFiddle), the menu disappears but requires two additional clicks on the ...

The sizing of Bootstrap Inline dropdown menus is not accurate

I want to create two dropdown menus using Bootstrap v3 that are displayed side by side with a specific width and utilizing the grid system. However, I am facing an issue where the width remains the same. Here is an example of what I mean: .menuList > ...

Can you explain the distinct variations between these two approaches for obtaining API data?

When working with third-party APIs in NextJS 14, I encountered two different methods to query the API that resulted in slightly different outcomes. Method 1: Located within the /api folder as a route handler: export async function GET() { const res = aw ...

Omit specific module from a webpack 4 chunk

Is there a way to exclude a specific module from being included in a chunk using webpack 4? For example, let's say I do not want lodash to be included in the vendor file at all costs. How can this be achieved? Here is the current configuration: spli ...

Adjust the width of the initial column in the table and ensure it remains noticeable

I am a beginner with bootstrap and I find it extremely useful. I have encountered a problem with a table I am working on. I am trying to set the width of the first column and keep it always visible, but I am having trouble achieving this. I have successful ...

What is the process for inserting a scroll bar within a div element?

   I have recently created a webpage using some divs, along with a bit of CSS and JavaScript. I am struggling to figure out how to add a scrollbar to one of my divs. The code is not overly complex, as it includes both CSS and JavaScript. <html> & ...

Having challenges retrieving information from MySQL in AngularJS

As a beginner in angularJS, I am trying to display all customers from MySQL. Here is the code I have written in the controller and service: app.controller('CustomersController', function ($scope, customersService, $http) { init(); function ini ...

Tips for positioning a div alongside its parent div

I have a unique setup with two nested divs that are both draggable. When I move the parent div (moveablecontainer), the child div (box.opened) follows smoothly as programmed. Everything works well in this scenario. However, when I resize the browser windo ...

What steps should I take to fix the error I'm encountering with React Material UI

import { AppBar, Toolbar, Typography } from '@material-ui/core' import React from 'react' import { makeStyles } from '@material-ui/styles'; const drawerWidth = 240; const useStyles = makeStyles((theme) => { return { ...

Experiencing migraines while integrating Firebase 9, Redux Toolkit, and Typescript in a React project. Encountering a peculiar issue where 'dispatch' is unexpectedly identified as type 'never'?

I am currently in the process of upgrading an old project to newer technologies, specifically focusing on Typescript, redux-toolkit, and Firebase v9 for modularity. While I have limited experience with Typescript and none with redux-toolkit, I have been us ...

Material-ui does not adjust Typography color based on the theme selected

Exploring material-ui, I have implemented two themes: const darkTheme = createMuiTheme({ palette: { type: "dark" } }); const lightTheme = createMuiTheme({ palette: { type: "light" } }); However, when utilizing the Typography component, t ...

The requested method in NEXT.js 14 is not permitted

I attempted to set up a basic post API in my NEXT.js 14 application with app routing. Here is the code I used: API call: useEffect(() => { const testFunc = async () => { const response = await fetch("http://localhost:3000/helpers/ed ...

Utilize React to transform PDF files into PNG images and seamlessly upload them to Cloudinary

Currently, I am utilizing react typescript and looking to select a PDF file, transform the PDF into an image, and then upload the final image onto Cloudinary. Although I have a service set up for uploading images in my Cloudinary media library, I am unsu ...

What could be causing the issue with Google Chart in my ASP MVC app?

My controller has a method that returns Json data. [HttpPost] public JsonResult CompanyChart() { var data = db.adusers; var selectUsers = from s in data where (s.Company != null) select s; int f ...

Get and show the response from a jQuery GET call

I'm currently working on fetching and displaying data using the ESV API available at Interestingly, the code seems to be functioning properly within the codecademy.com domain but is encountering issues on the esvapi.org domain. Here's a lin ...

Learn the method of showcasing a JavaScript variable value within an HTML href tag

Currently, I am in the process of rewriting my URL and category name to be passed into the URL. For this purpose, I am creating a URL friendly string using the following JavaScript function: function getUrlFriendlyString(str) { // convert spaces to &ap ...