Is it possible to dynamically alter a CSS property using styled components when an onClick event occurs?

Hey there, I'm pretty new to React and currently exploring styled components for the CSS styling of my components. One of the components I've created is a button called SummonButton:

const SummonButton = styled.button`
    height: 50px;
    border: none;
    outline: none;
    color: #fff;
    background: #111;
    cursor: pointer;
    position: relative;
    z-index: 0;
    border-radius: 10px;
    font-size: 1.5em;

    :before {
        content: '';
        background: linear-gradient(45deg, #ff0000, #ff7300, #fffb00, #48ff00, #00ffd5, #002bff, #7a00ff, #ff00c8, #ff0000);
        position: absolute;
        top: -2px;
        left:-2px;
        background-size: 400%;
        z-index: -1;
        filter: blur(5px);
        width: calc(100% + 4px);
        height: calc(100% + 4px);
        animation: glowing 20s linear infinite;
        opacity: 0;
        transition: opacity .3s ease-in-out;
        border-radius: 10px;
    }

    :active {
        color: #000
    }

    :active:after {
        background: transparent;
    }

    :hover:before {
        opacity: 1;
    }

    :after {
        z-index: -1;
        content: '';
        position: absolute;
        width: 100%;
        height: 100%;
        background: #111;
        left: 0;
        top: 0;
        border-radius: 10px;
    }

    @keyframes glowing {
        0% { background-position: 0 0; }
        50% { background-position: 400% 0; }
        100% { background-position: 0 0; }
    }

Now, I want to limit this SummonButton so that it stops functioning after being clicked ten times. To achieve this, I added the following line of code:

<SummonButton onClick={summonAble < 10 ? SummonAction : {backgroundColor: "red"}}>Summon</SummonButton>

The summonAble state increments by one every time SummonAction is triggered. Once the count reaches 10, I'd like to change the background color of the button to red. Any ideas on how I can accomplish this?

Answer №1

In order to keep track of the number of clicks, you will need to store this information in a variable.

const [numClicks, setNumClicks] = React.useState(0);

Next, make sure to include a prop in the SummonButton component to determine if the condition has been met:

<SummonButton onClick={...} isRed={numClicks > 9} />

const SummonButton = styled.button`
   background: ${({ isRed }) => isRed ? 'red' : 'black'};
   ...
`;

Important: Don't forget to call the setNumClicks function within every onClick event handler.

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 can you align two div elements side by side, if the first div is spanning across two lines?

I'm looking to position two divs next to each other, with the second div starting right where the first one ends. I came across a similar question on Stack Overflow, but unfortunately, it didn't have the answer I needed. <div id="wrapper"> ...

Utilizing Inquiries within Arrays

I've been working on a quiz application and I have successfully built the array with questions and answers. However, I'm facing some challenges in getting the next question to display after clicking the submit button. Here is a snippet of the cod ...

How to fetch React route parameters on the server-side aspect

I encountered a challenge while working with ReactJS and ExpressJS. The user uploads some information on the /info route using React and axios. Then, the user receives route parameters from the server side to redirect to: axios.post('/info', Som ...

Preventing Flash of Unstyled Content in ElectronJS Browser Windows

Upon creating a new BrowserWindow and utilizing loadURL to incorporate an html file within the renderer, there is a brief instance where unstyled content is displayed for approximately half a second before the css is loaded. window.loadURL('file://&a ...

Is receiving an error message about a "stray start tag footer" in your HTML validator?

I am perplexed by the error message I am receiving: Stray start tag footer. All I have included here is the tags: <!doctype html> <head> <title>title</title> <meta charset="UTF-8"> <meta name="keywords" cont ...

Comparable to LINQ SingleOrDefault()

I frequently utilize this particular pattern in my Typescript coding: class Vegetable { constructor(public id: number, public name: string) { } } var vegetableArray = new Array<Vegetable>(); vegetableArray.push(new Vegetable(1, "Carrot")); ...

How to efficiently transfer data between PHP and Javascript using ajax?

Struggling greatly with the ajax function within the jQuery library. As a beginner in jQuery, ajax, and php, I am currently engaged in a school project that involves creating a game-like environment where a 10x10 table generates numbers, selects a cell aut ...

It's possible for anyone to enhance the appearance of the Download button by adding styles without compromising its functionality

Looking to enhance the style of the Download button as it appears too formal. Seeking assistance in adding some button styles to make it more stylish. The code is correct, just aiming to give the Download button a trendy look with specified styles. ...

Adjustable pseudo-elements derived from the size of the element

I have a unique feature in my web application that involves a span element with inner text and additional :before and :after pseudo-elements used as decorative lines on each side of the text. Check out this JSFiddle example to see exactly what I mean. .c ...

What could be causing my media query to not function properly?

I've been experimenting with some basic media queries but am encountering an issue with the div element that has the class "container." Whenever I adjust the screen size to be between 992px and 1200px, the div disappears from the page. It's perpl ...

What is the best way to retrieve information from an http website and display it in an html table using javascript

I am attempting to retrieve data from the specified site: . The website appears to feature a list of objects, and my goal is to extract each object enclosed in {} into separate columns within a row (6 columns total - one for gameNumber, one for teams, and ...

Enhancing Filtering Capabilities with Multiple ng-Model in AngularJS

I am facing an issue with filtering a form based on user input in a text box or selection from a dropdown list. The text box filter works fine individually, but when I try to combine it with the dropdown list selection, neither filter seems to work. Below ...

Ensure to verify the dimensions and size of the image prior to uploading

Is there a way to check the dimensions of an image using this function? I want to verify it before uploading... $("#LINK_UPLOAD_PHOTO").submit(function () { var form = $(this); form.ajaxSubmit({ url: SITE_URL + 'functions/_app/execute ...

Apply a border to the div that has been selected

I have a tool for storing information and I am using *ngFor to display each instance in a line. Is there a way to add a border when clicking on a line? The border should only appear on the clicked line, disappearing from the previous one if another line i ...

Creating a two-column grid layout using Bootstrap 4 is a simple and efficient process. Let's see how

I've been struggling to get this to display side by side in a two-column grid. Even after following Bootstrap tutorials, I can't seem to make it work. Check out the code below: <div class="row"> <div class="col-md-8 ...

What could be causing XMLHttpRequest to encounter issues with the readystate and status states while running on localhost

Hey guys, I'm having some trouble with this code and can't figure out why it's not working. Here is the code snippet: <script> function findMatch() { if(window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); ...

Discrepancy in div height between Chrome/Edge and Firefox browsers

I am currently in the process of designing a straightforward website layout that includes a navigation bar at the top. The main focus is on an image that needs to stretch from the bottom of the navbar to the bottom of the window, filling up the entire scre ...

A guide to storing a JavaScript variable in a MySQL database using Express.js

Looking for some guidance on node js and expressjs framework. While developing a web application, I've encountered an issue with saving data into the database. Everything seems to be set up correctly, but the data stored in the variable (MyID) is not ...

Error in Next.js API Application: TypeError - Unable to access property 'map' of undefined

I have recently started using Next.js and am working on a project to create a dynamic website that pulls data from an API. The website must have a minimum of two pages: one index page and another page to display details about the selected topic from the in ...

Is there a simple method to verify if an element has been properly enabled or disabled upon clicking a checkbox?

I have a component that includes a <Switch/> (using Material-UI) and a <TextField/>. When the user clicks on the Switch, it toggles the enabled/disabled state of another TextField. The code functions correctly, but my JEST test always fails. .. ...