Having trouble with applying CSS conditionally in React JS with Typescript?

I'm currently facing an issue with my code where I want the Box to stay highlighted with a black border when clicked. Here's the snippet:

interface BigButtonProps {
  onClick(): void;
    Title: string;
    Description?: string;
    startIcon?: React.ElementType;
}

const BigButton: FC<BigButtonProps> = (props: BigButtonProps, { active }) => {
  const [isClicked, setClicked] = useState(false);
  const clickMe = () => {
    setClicked(!isClicked);
    console.log("say hello");
  };
  const SvgIconStyles: CSS.Properties = {
    display: "block",
  };
  const BoxStyles: CSS.Properties = {
    border: "1.5px solid black",
  };

  const BoxStylesActive: CSS.Properties = {
    border: "1.5px solid black",
  };
  return (
    <Box
      sx={{
        height: {
          xs: "45px",
          md: "100px",
        },
        width: {
          xs: "45px",
          md: "300px",
        },
    borderRadius: "10px",

    boxShadow: "0 2px 3px 2px rgba(0, 0, 0, .125)",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    flexDirection: "column",
    ":hover": {
      border: "1.5px solid blue",
    },
  }}
  className={classNames("BoxStyles", { BoxStylesActive: isClicked })}
  onClick={() => {
    clickMe();
  }}
>
  <Typography variant="h1">{props.Title}</Typography>

  <Typography variant="subtitle1">{props.Description}</Typography>
  <SvgIcon
    component={CheckCircleIcon}
    sx={{
      display: "block",
    }}
  />
</Box>


);
};

export default BigButton;

My challenge is that although the border color changes to solid black upon clicking due to CSS active, it doesn't remain that way. I tried conditionally applying CSS by creating methods with the property type CSS.Properties in TypeScript for this react component, but it's not working as expected. Any insights on what might be going wrong here?

Answer №1

If you want to experiment, consider the following:

<Box styles={isClicked ? BoxStylesActive : BoxStyles}>
// ...

Take note that BoxStylesActive and BoxStyles appear identical in the code you pasted. So if there are no changes, don't be surprised.

<Box sx={{border: isClicked ? "1.5px solid black" : none}}>
// ...

You can also try this alternative approach.

In this scenario, you're combining the sx prop with styles. Additionally, remember that your BoxStylesActive is an object, not a CSS class. Therefore, applying classNames() won't impact it.

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

Unable to Add Dependency to Subclassed Object

In my setup, there are three classes that interact with each other. I am utilizing inversify for handling dependency injection. However, I encountered an issue when I injected the class MessageBroker into the derived class Repository and found that the Mes ...

I incorporated a CSS file from another HTML document. What do you think about that?

In my work with Ionic 3 and angular 4, each HTML file is accompanied by its own CSS file. There are times when I reference a class in one HTML file that is defined in another HTML file. I have observed that this CSS class gets injected into the main.js He ...

Issue: Cypress binary download unsuccessful

Today, my Nextjs and Vercel deployment setup is causing an issue with Cypress. Everything was working fine yesterday, but now when Vercel runs the build, I'm encountering this error: https://i.sstatic.net/KanRL.png I realized that Vercel installed C ...

Initiate a Material-UI CSS animation when the element comes into the viewport

After conducting some research on CSS animation triggers when an element comes into view, I came across this solution that utilizes the IntersectionObserver and element.classList.add('.some-class-name') While this method is demonstrated in pure ...

Unexpected alteration of property value when using methods like Array.from() or insertAdjacentElement

I'm encountering an issue where a property of my class undergoes an unintended transformation. import { Draggable, DragTarget } from '../Models/eventlisteners'; import { HeroValues } from '../Models/responseModels'; import { Uti ...

Determine data type based on key of object within a Zod array

Trying to extract the type from a key within an array of objects using Zod presents some challenges, especially when the array is nested within another object. To illustrate the issue: const obj = z.object({ nestedArray: z.array(z.object({ valueIWant: z ...

'This' loses its value within a function once the decorator is applied

Scenario: Exploring the creation of a decorator to implement an interceptor for formatting output. Issue at Hand: Encountering 'this' becoming undefined post application of the decorator. // custom decorator function UseAfter(this: any, fn: (.. ...

``I'm having trouble getting a fetch request from React to Express to function

I am encountering a 404 not found error when trying to fetch data from React to Express. Below is the client-side code: deleteRoom(roomId){ console.log('this is the current user in delete room', this.state.currentUser); fetch('htt ...

Handling errors when using react-query's mutateAsync function

Currently, I am delving into learning the react-query library and I am eager to utilize the mutateAsync function within the useMutation API. Below is the snippet of my code: import { useMutation } from "react-query"; const asyncCall = () => { ...

Import resolves Uncaught ReferenceError by preventing access to 'xx' before it is initialized

Currently, I am troubleshooting a peculiar error that has come up. Within my service file where all other services are stored, I have included the import of one component along with all the other services required by the frontend. import { VacationComponen ...

Tips for designing a unique custom scrollbar

I'm in need of some CSS expertise to help me create a custom scroll bar that resembles the one shown in the image. The key requirement is for the background to be transparent, although I've temporarily positioned it against a green backdrop. ...

Issue with Gulp 4 and browser-sync // Tasks that have not finished: browser-sync

I am struggling to understand the error regarding browser-sync in gulp 4, as there is no clear documentation about it. Even in the gulp 4 documentation, the usage of "async" is not clear. How can I troubleshoot and fix this issue? Thank you. bla bla bl ...

Troubleshooting TS Errors in Vue 3 and Vite with Typescript Integration

Currently experimenting with Vue 3, Vite, and TypeScript to build a Vue project. The configuration process has proven to be quite challenging. Despite consulting various documentation sources, I have not been successful in achieving my desired outcome. My ...

Creating a responsive grid division

.subcategory-main-wrapper { display: grid; grid-template-columns: repeat(4, max-content); position: absolute; width: 100%; column-gap: 4%; justify-content: center; height: 360px; @media @tabletScreens { height: 280px; } @media @ ...

In Ionic 3, the term "Twilio" is not recognized

Attempting to integrate Twilio into my Ionic 3 application has been a bit of a challenge. While it works fine when tested on a browser, running it on an actual device led to a frustrating error message: TypeError: undefined is not a function {stack: (...), ...

In order to effectively manage the outcome of these loaders, it might be necessary to incorporate an extra loader into the equation. Node.js version

./node_modules/html-to-react/node_modules/htmlparser2/lib/esm/index.js 67:9 Module parse failed: Unexpected token (67:9) File was processed with these loaders: * ./node_modules/babel-loader/lib/index.js You may need an additional loader to handle the resu ...

Alignment of input

        <section class="newsletter text-white text-center"> <div class="container"> <div class="row"> <div class="col-xl-9 mx-auto"> <h2 class="mb-4" ...

Solution for repairing the display location button on Android within a React Native Map

I am facing an issue with the Location Button in my React Native Maps app. When the app is opened for the first time and the map is rendered, the button disappears. However, if I close the app but leave it running in the background, upon reopening the app, ...

`Positioning of inline-block elements`

I am encountering an issue with the display CSS attributes set for three tags: a - inline-block img - block span - inline <a id="first"> <img/> <span> A first line of text B second line of text </span> </a> <a id="secon ...