The ternary operator is malfunctioning when it comes to the condition

I've encountered an issue while trying to integrate a custom MUI button into my project. My goal is to have the button enabled only when 2 specific objects are not empty, otherwise it should remain disabled. Despite my efforts, the code I've written is only partially effective.

My intention is to activate the button only when both conditions are met, however, it currently becomes enabled if just one condition is satisfied. It seems that the ternary operation is not recognizing the '&&' logical operator.

How can I address this challenge?

{Object.keys(userSelectDevicename).length === 0 && Object.keys(userSelectDevicecategory).length === 0 ? (
  <>
    {" "}
    <WsButton type="submit" size="small" variant="contained" disabled={bool}>
      Add
    </WsButton>
  </>
) : (
  <>
    {" "}
    <WsButton type="submit" size="small" variant="contained" disabled={!bool}>
      Add
    </WsButton>
  </>
)};

Answer №1

Each situation has two JSX elements that are identical. The only thing that changes is disabled={!bool}. While you could use a ternary operator for this, I prefer to take a different approach as shown below. This approach helps in keeping the code more organized by creating a function that determines the disabled state of the button.

export default function YourComponent(){

   function checkButtonState(){
      let lengthOne = Object.keys(userSelectDevicename).length
      let lengthTwo = Object.keys(userSelectDevicecategory).length

      if(lengthOne === 0 && lengthTwo === 0) return true
      else return false
   }
     
   return(
      <>
       {" "}
       <WsButton type="submit" size="small" variant="contained" disabled={!checkButtonState()}>
          Add
       </WsButton>
      </>
   ) 
}

Answer №2

Place both conditions within parentheses to ensure correct evaluation. The && operator acts as a conditional operator, checking the

Object.keys(userSelectDevicename).length === 0
condition first. If it is true, the second half of the code will execute - represented by
(Object.keys(userSelectDevicecategory).length === 0) ? ....

By enclosing the conditions in parentheses, their priority increases and they are evaluated together before the ternary operator makes a decision based on the combined result.

 {(Object.keys(userSelectDevicename).length === 0 && Object.keys(userSelectDevicecategory).length === 0) ? (
                          <>
                            {" "}
                            <WsButton type="submit" size="small" variant="contained" disabled={bool}>
                              Add
                            </WsButton>
                          </>
                        ) : (
                          <>
                            {" "}
                            <WsButton type="submit" size="small" variant="contained" disabled={!bool}>
                              Add
                            </WsButton>
                          </>
                        )}

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

How come I am unable to save an array of objects in a State within React JS?

React JS component: When I make a request to the backend to fetch data stored in a MySQL table, it returns an array of objects. I store this data in a state called `favcoin`. However, when I console.log(favcoin), it displays an empty array [ ]. Strangely, ...

Stop Browsers from Saving the Current Page in the History Log

Currently, I am facing an issue with a user-triggered popup window on my website that redirects to another site. It is important that users do not access this page directly and only navigate to it if the popup window opens as intended. mysite.com -> my ...

Unusual behavior of Typescript with Storybook's addon-docs

I'm trying to integrate storybook addon-docs into my TypeScript React project. Everything seems to be almost working, but I've noticed that the file name is affecting how the props type table gets rendered. Here is my file structure: src - Butto ...

Failing to send contact information using JSON in PHP

I attempted to transmit JSON data to PHP for email processing, but encountered an issue where the process veered into the 'else' condition during debugging. Here is the code snippet: HTML <form id="cbp-mc-form" class="cbp-mc-form" method="po ...

User interface for modifying options in a dropdown menu

I seem to be facing a terminology dilemma. Currently, I have a database with values stored in a table that need to be displayed in a select drop-down on a web interface. The technology stack includes SQL Server, ColdFusion, and JavaScript, mainly jQuery. ...

Error: 'delay' is not recognized as a valid function

I'm encountering an error message that reads as follows: $("div.valid_box").html(data.message).css("margin-left", "145px").css("width", "520px").show().delay is not a function [Break On This Error] $(...elay(10000).hide("slow", function() { within m ...

retrieving attribute values from JSON objects using JavaScript

I am struggling to extract certain attribute values from a JSON output and use them as input for a function in JavaScript. I need assistance with this task! Below is the JSON data that I want to work with, specifically aiming to extract the filename valu ...

What steps should I take to resolve issues with the npm installation on Linux?

I'm encountering an issue while attempting to use npm install in order to install a package. Despite my attempts to update and re-download from the root directory, I am unable to resolve the error. hackathonday1-2 git:(save-button) ✗ npm install f ...

Error in Compiling HTML Elements Collection<<Element>

Currently, I am developing an eCommerce application that features a popup window for users when they click on "Add to Cart." This popup allows users to select product variations and quantities before adding the item to their cart. The popup consists of a s ...

Strategies for resolving duplicate jQuery code in my project

Trying to simplify my jQuery code that handles video selection and playback functionality. Users can click on a thumbnail or button to play a specific video, with the title of the video changing accordingly. Despite achieving the desired outcome, the cur ...

Assistance with JavaScript Regular Expressions for formatting BBCode

A few weeks ago, I stumbled upon this regex expression: /([\r\n])|(?:\[([a-z\*]{1,16})(?:=([^\x00-\x1F"'\(\)<>\[\]]{1,256}))?\])|(?:\[\/([a-z]{1,16})\])/ig It's designe ...

Retrieving information from PHP using AJAX

As a newcomer to the world of AJAX, I am faced with the task of retrieving data from a PHP file and storing it in a JavaScript variable. Despite exploring several examples, I have not been able to find a satisfactory solution. Here is a simplified HTML cod ...

Issue with `styles` argument after updating from Material version 4 to 5: MUI

After recently upgrading from Material V4 to V5, I encountered the following error message: MUI: The `styles` argument provided is invalid. You are providing a function without a theme in the context. One of the parent elements needs to use a ThemeProvider ...

Retrieve information about the clicked item using the Backbone framework

I have a unique webpage that showcases an impressive collection of books. Each book listed on the page comes with essential information such as the title, price, and description. This data is imported from a JSON file. Excitingly, when users click on any ...

Trouble with Styling React-Toastify in TypeScript: struggling to adjust z-index in Toast Container

Currently in the process of developing a React application utilizing TypeScript, I have incorporated the React-Toastify library to handle notifications. However, encountering some challenges with the styling of the ToastContainer component. Specifically, ...

Creating a promise in an AngularJS factory function to perform an operation

When working within an Angular factory, I am tasked with creating a function that must return a promise. Once the promise is returned, additional functionality will be added. SPApp.factory('processing', ['$http', '$rootScope&a ...

What is the more efficient approach: retrieving all data in one request or making individual requests for each piece?

When it comes to performance, which method is more efficient: 1) Retrieving 100 records in a single fetch request 2) Fetching each data row individually (100 times) P.S. I am using the axios library ...

React Tabulator - custom header filter for select column - hide 'X' option

Is it possible to remove the 'x' option on header filters in react tabulator columns? The issue arises when users click the 'X' to clear a filter, as expected. However, if they then try to click on the same filter for another list item ...

In the realm of JavaScript, the localeCompare() string method is more than willing to accept the presence of 'undefined' as a valid parameter for 'locale', while opting to outright reject any instance of

I have discovered a method to sort strings naturally const rows = ['37-SK', '4-ML', '41-NP', '2-YZ', '21', '26-BF']; console.log(rows.sort((a, b) => a.localeCompare(b, undefined, { numeric: tru ...

Unleashing the power of creativity: Crafting distinctive keys for React elements

I have been working on a React application that enables users to create and save lists. However, I am encountering a warning from React stating that my elements (List/ListForm) do not have a unique key prop. How can I generate a unique key prop for user-ge ...