Having trouble applying class names in ReactJS using a switch statement

I need help troubleshooting an issue where badges are not rendering in different colors based on the payment status of an order. I keep receiving an error message stating;

buttonColour is not defined
{(() => {
    let buttonColour

    switch (paymentstatus) {
        case "Paid": return buttonColour = "bg-green-100 text-green-800"
        case "Pending": return buttonColour = "bg-yellow-100 text-yellow-800"
        case "Failed": return buttonColour = "bg-red-100 text-red-800"
    }
})()}
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
    <span className={`${buttonColour} inline-flex items-center rounded-md px-2.5 py-0.5 text-sm font-medium`}>{paymentstatus}</span>
</td>

Answer №1

{(() => {
let colorOfButton

switch (status) {
    case "Complete": return colorOfButton = "bg-green-100 text-green-800"
    case "Processing": return colorOfButton = "bg-yellow-100 text-yellow-800"
    case "Failed": return colorOfButton = "bg-red-100 text-red-800"
}
})()}

In this code snippet, the variable colorOfButton is confined to the block scope and cannot be accessed externally.

<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
<span className={`${colorOfButton} inline-flex items-center rounded-md px-2.5 py-0.5 text-sm font-medium`}>{status}</span>

Therefore, using colorOfButton outside of its scope is not allowed.

It is recommended to encapsulate the logic in a separate hook that updates the button color when the status changes.

utilizeStatus.jsx

import { useEffect, useState } from "react";

export default function utilizeStatus(status) {
  const [buttonColor, setButtonColor] = useState("");
  useEffect(() => {
    switch (status) {
      case "Complete":
        setButtonColor("bg-green-100 text-green-800");
        break;
      case "Processing":
        setButtonColor("bg-yellow-100 text-yellow-800");
        break;
      case "Failed":
        setButtonColor("bg-red-100 text-red-800");
        break;
      default:
        setButtonColor("");
    }
  }, [status]);
  return {
    buttonColor
  };
}

Then, in your main App component:

import "./styles.css";
import utilizeStatus from "./utilizeStatus";

export default function App() {
  const status = "Processing";
  const { buttonColor } = utilizeStatus(status);

  return (
    <div className="App">
      <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
        <span
          className={`${buttonColor} inline-flex items-center rounded-md px-2.5 py-0.5 text-sm font-medium`}
        >
          {status}
        </span>
      </td>
    </div>
  );
}

Answer №2

There seems to be a scope issue here. The variable buttonColor is not accessible within the span.

I recommend trying a different approach.

const classes = {
  "Paid": "bg-green-100 text-green-800",
  "Pending": "bg-yellow-100 text-yellow-800",
  "Failed": "bg-red-100 text-red-800",
}

Update your span as follows -

<span className={`${classes[paymentstatus] || ''} inline-flex items-center rounded-md px-2.5 py-0.5 text-sm font-medium`}>{paymentstatus}</span>

If you prefer using a switch statement, you can create a function and call it accordingly.

For example:

const getClasses = useCallback( (paymentstatus) =>{

    let buttonColour  = '';
    switch (paymentstatus) {
        case "Paid": 
            buttonColour = "bg-green-100 text-green-800"; 
            break
        case "Pending": 
            buttonColour = "bg-yellow-100 text-yellow-800";
            break;
        case "Failed": 
            buttonColour = "bg-red-100 text-red-800";
            break;
         default:
    }
}, []);

Incorporate this into your span like so:

<span className={`${getClasses(paymentstatus)} inline-flex items-center rounded-md px-2.5 py-0.5 text-sm font-medium`}>{paymentstatus}</span>

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

The host name specified in the _document.js file within a NextJS project

Is it possible to obtain the hostname in the _document.js file within nextJS without access to the window object during server-side rendering? I attempted to retrieve it from initialProps (context), yet the req in initialProps remained undefined. Are the ...

Creating videos with NEXTJS

I am currently developing a website using NextJS and I encountered an issue when trying to set a video as the background. Initially, everything works perfectly during the first render, but upon reloading the screen, the video no longer plays in autoplay mo ...

Refreshing GIF images in React using forceReload

In order to restart the gif animation every 12 seconds or whenever the activeIndex changes, I need to reload a GIF image with CHECKMARK_ANIMATION_ICON as the source. Below is the code: const reloadImgSource = (imgSource) => { setTimeout(() =& ...

Implementing a Scroll Bar within a Stack Component in Material UI

I've developed a component and now I'm looking to enable scrolling when it expands beyond the screen width <Stack direction="row"> <Stack gap={1} overflow="auto"> {fields.map((el, i) => ( ...

The implementation of race in React Redux Saga is proving to have negligible impact

I have implemented the following saga effect: function* loginSaga() { const logoutTimeoutCreationDate: string | null = yield localStorage.getItem('logoutTimeoutCreationDate'); let logoutTimeout: number; if (!logoutTimeoutCreationDate || + ...

A comprehensive guide on utilizing the loading.tsx file in Next JS

In the OnboardingForm.tsx component, I have a straightforward function to handle form data. async function handleFormData(formData: FormData) { const result = await createUserFromForm( formData, clerkUserId as string, emailAddress a ...

Route Handler 13 is encountering difficulties in retrieving data from the body in the (app/api/auth) endpoint

Whenever I attempt to retrieve the body from the new export async function POST( req: Request), it seems to come through as a stream instead of the expected content type. The route handler can be found in api/auth/signup See folder layout image export asyn ...

Creating curved triangles in React Native is a fun and easy way to add stylish

Hello everyone, I am a newcomer to react native and I am attempting to create the following user interface. Is there any way to create a curved triangle? I have tried but I am unable to curve the edges of the triangle. https://i.stack.imgur.com/vE17U.png ...

Next.js is causing an error by not recognizing the document variable

While diving into the world of next.js, I encountered an interesting challenge. In my project, I came across this puzzling error. The culprit seemed to be a module called Typed.js, which threw me off with a peculiar message: Server Error ReferenceError: d ...

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 ...

What could be causing my Alert component to keep triggering repeatedly?

This is my custom React Native script. import React, { useState, useEffect } from 'react'; import { Alert, View, Image, StyleSheet, Animated, Easing, TouchableOpacity, Text, ScrollView, ImageBackground, Dimensions, TextInput } from 'react-na ...

The type 'TaskListProps[]' cannot be assigned to type 'TaskListProps'

I'm struggling with handling types in my TypeScript application, especially with the TaskListProps interface. export default interface TaskListProps { tasks: [ { list_id: string; title: string; description: string; status ...

Creating a centered and beautifully styled picture with a specific maximum size using React

I recently completed the development of a new website, which can be viewed at Upon inspection of the website, it is evident that the photo is not centered and appears too large on mobile phones. Despite my efforts to align it using various methods outline ...

Exploring Nested Data in MERN Stack Frontend Development

Here is the structure of my model: coverPhoto: { type: String, required: true, }, images: [{ type: String }], location: { address: { type: String, required: true }, city: { type: String, required: true }, postalCode: { type: Number, required: ...

Encountering a 403 Forbidden error while attempting to access a website built with Next.js

Every time I try to access the Next.JS website that's been deployed on IIS using the HTTP address, I'm faced with this error message: Get http://...../_next/static/chunks/webpack-73760e2208a549db.js net:: ERR_ABORTED 403 (Forbidden) However, w ...

Issue with getStaticProps functionality on Vercel seems to be persisting

UPDATE: I realize now that my mistake was calling my own API instead of querying the MongoDB database directly in getStaticProps(). I have made the necessary changes: export async function getStaticProps() { await dbConnect(); const user = await User.find ...

What is the most effective method for displaying a child modal within a map?

Project link: Check out my project here! I have two key files in my project - App.js and PageFive.js. In App.js, there is an array defined as follows: state = { boxes: [ { cbIndex: "cb1", name: "Bob" }, { cbI ...

Error! React is unable to find the window object

I recently added the "react-speech" package to my application in order to incorporate text-to-speech functionality. However, upon importing the package, I encountered an error that has been challenging to resolve despite extensive research. Any assistance ...

Error: Unable to locate named export for 'express'

I am facing an issue with my CRUD project developed using react and nodejs. When I attempt to run index.js, a strange error pops up: Named export 'express' not found (please refer to the image for details). The code in my index.js file is as fol ...

React - utilize a variable as the value for an HTML element and update it whenever the variable undergoes a change

I'm on a mission to accomplish the following tasks: 1.) Initialize a variable called X with some text content. 2.) Render an HTML paragraph element that displays the text from variable X. 3.) Include an HTML Input field for users to modify the content ...