Effortlessly alter the appearance of Stripe Elements using Next-themes for dynamic style changes

I've been working with Stripe Elements and implementing dynamic changes to input styles based on the theme. Everything is functioning as intended, but I'm running into an issue when switching themes while on the page containing the Stripe Elements input - I have to hard refresh the page in order for the CSS changes to take effect.

My goal is to enable the styles to update automatically when the theme changes, specifically focusing on changing the backgroundColor.

Here's the current implementation:

import { useTheme } from "next-themes";

 const { resolvedTheme, setTheme } = useTheme();

  const CARD_OPTIONS = {
    iconStyle: "solid",
    style: {
      base: {
        backgroundColor: `${resolvedTheme === "dark" ? "black" : "white"}`,
        iconColor: "#6D28D9",
        color: `${resolvedTheme === "dark" ? "white" : "#9CA3AF"}`,
        fontWeight: "500",
        fontFamily: "Roboto, Open Sans, Segoe UI, sans-serif",
        fontSize: "16px",
        fontSmoothing: "antialiased",
        ":-webkit-autofill": {
          color: "#fce883",
        },
        "::placeholder": {
          color: "#D1D5DB",
        },
      },
      invalid: {
        iconColor: "#ef2961",
        color: "#ef2961",
      },
    },
  };

<CardElement options={CARD_OPTIONS} />

Another approach I experimented with involves using mount and passing DARK_CARD_OPTIONS to the Card Element.

Like this:

const [mounted, setMounted] = useState(false);

useEffect(() => setMounted(true), []);

 const DARK_CARD_OPTIONS = {
    iconStyle: "solid",
    style: {
      base: {
        backgroundColor: "red",
        iconColor: "#6D28D9",
        color: "white,
        fontWeight: "500",
        fontFamily: "Roboto, Open Sans, Segoe UI, sans-serif",
        fontSize: "16px",
        fontSmoothing: "antialiased",
        ":-webkit-autofill": {
          color: "#fce883",
        },
        "::placeholder": {
          color: "#D1D5DB",
        },
      },
      invalid: {
        iconColor: "#ef2961",
        color: "#ef2961",
      },
    },
  };

  {mounted && (
          <div className="p-4 rounded-lg border border-gray-800 dark:border-gray-600 focus:border-purple-700">
            {resolvedTheme === "dark" ? (
              <CardElement options={DARK_CARD_OPTIONS} />
            ) : (
              <CardElement options={CARD_OPTIONS} />
            )}
          </div>
        )}

However, this method seems to only result in certain areas of the CardElements input updating dynamically.

Please refer to the screenshots below (highlighted in red):

https://i.sstatic.net/4Tx8P.png

https://i.sstatic.net/ym3CQ.png

Answer №1

In order to make the CardElement function properly when the theme changes, you must remount it forcefully:

<CardElement key={resolvedTheme} options={CARD_OPTIONS} />

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

Exploring the implementation of TypeScript conditional props alongside the useContext hook

Currently, in the application I am developing, there is a component named InputElement. This component allows different HTML inputs such as input, textarea, select, etc to share common styles and properties when used with react-hook-form. type Variant = ...

How come attempting to read a nonexistent document from Firestore results in an uncaught promise?

I've been struggling to read and display data from Firestore, but I keep seeing error messages in the console. Encountered (in promise) a TypeError: Unable to read properties of undefined (reading 'ex') Encountered (in promise) a TypeError ...

The Telegram Login component is not displaying properly within a React single-page application

I am currently working on a React frontend application that was created using create-react-app, with Django running at the backend. We have separate development and production environments, each with its own domain. My goal now is to integrate a widget int ...

Having trouble loading SVG component in Next.js with SVGR integration

I recently obtained an SVG react component that was automatically converted from the SVGR playground page. I integrated it into my project and followed the installation instructions for @svgr/webpack and configured the setup as advised. However, upon loadi ...

Tips for identifying issues with a malfunctioning filter in ReactJS

Upon attempting to delete unwanted data by clicking the "delete" button using filter, I am encountering an issue where it is not working and there are no bug notifications. This leaves me unsure of how to proceed with my project. import ColorCards from &qu ...

Manipulating contextual selectors

Have you ever tried reverting or overriding attributes from contextual selectors? .card { padding-top: 20px; ... } .card .card-header { padding: 0 20px; } .card .card-header.news { padding-top: 0px; } Do you think it's possible to elimina ...

How can you address `act(...)` warnings associated with material-ui animations when using testing-library/user-event?

It's clear to me that including act() around user events is unnecessary since the testing library handles it automatically. However, despite this knowledge, I still receive warnings if I omit it. An instance of this is with a Material-UI component fea ...

Having difficulty retrieving images in a React Native project

I'm having difficulty importing and using an image because it doesn't seem to recognize the images no matter what path I try. click here for image description click here for image description I've even tried right-clicking and copying both ...

In Express, data is not retained across different routes within a session

My login system uses Node.js (Express) for the back-end and React.js (with Redux) for the front-end. I am encountering an issue where the user session is getting lost when making a request to another route. Despite configuring the session correctly in my E ...

Utilizing flexbox, absolute positioning, and 100% height in web design

While experimenting with a flexbox inside an absolute box within a div of defined height, I encountered a problem. Let me explain the issue step by step. Here is a link to a fiddle demonstrating the problem: https://jsfiddle.net/8ub9tyub/ When hovering o ...

Is it possible to define the sequence of wrapped items in CSS flexbox?

I am using a <div> with CSS flex to maintain responsiveness. I want to control the order in which elements are wrapped. For instance, I need 1 - 2 - 3 To be rearranged as 1 3 2 Once fully wrapped. Here is my current code: https://jsfiddle.net/ ...

What is the best way to create rounded edges for a spinning spinner using CSS?

Check out my fiddle link here! I managed to create a spinning spinner using CSS, however, I am struggling to round the edges of the black part that is spinning/moving. Can someone help me achieve this effect? .loader { position: relative; border: ...

Incorporating Node modules within a Spring Boot executable JAR

I am currently working on a Spring Boot application with a React front end. In my project, I have node dependencies managed by package.json and Spring Boot dependencies handled by Gradle. As I prepare to build a jar for my production environment, I am unc ...

Steps to making an overlapping sidebar with Bootstrap column

I'm trying to set up a sidebar in Bootstrap that overlaps with a column. The goal is for the sidebar to appear when a button is clicked and disappear when the close button x is clicked. Despite using a Bootstrap row and column layout, I encountered is ...

Refactor the process of passing props as an array of React elements

I recently implemented the recompose library into my project and so far, it's been working really well. However, I've encountered a problem when trying to pass default props of react elements. When I try to call the mapOptions Function, I get a ...

Why isn't the image adjusting its size to fit the container it's placed in? Am I missing something?

My issue involves getting an image to resize and stay within its designated div. However, the image continues to spill over onto the div below when I adjust the browser size or view it on my laptop. I have not set any fixed dimensions for the image. I am ...

Increasing specificity to override styles in Material UI aesthetically

Is there a way to override a highly specific class rule? Take, for instance, the .MuiAccordionSummary-content.Mui-expanded class within the AccordionSummary const useStyles = makeStyles(() => ({ expanded: { marginBottom: 0, }, })); whe ...

Adjust image size dynamically while keeping the original aspect ratio

Is there a way to scale variable portrait and landscape images dynamically to fit proportionally within a browser window? You can find my current image resizing attempt here: http://jsfiddle.net/6pnCH/4/ I would like the image to be already scaled vertic ...

Width of a floating division

I have been attempting to adjust the width (or max-width) of a floating div, but so far, none of the options I've tried have been successful. Below is the HTML code I am working with: <div class="tab-content"> <div id = "basicInfo" clas ...

How can I avoid anti-aliasing in browsers when enlarging images?

Back in April 2012, Google's Chart Image API became deprecated but it was possible to generate QR codes using it. Although I know that I can adjust the size of the image produced by the API, I prefer to simply use CSS along with the width and height ...