Enhancing React Applications: Implementing Dynamic CSS Modifications

I have a component that includes an input slider controlled by radio buttons.

<input
 checked={settings[0]?.payments.length === 1 ? 'checked' : null}
 type='radio'
 id={payment.value}
 value={payment.value}
 onChange={
   settings[0]?.payments.length === 1
   ? setState(payment.value)
   : handleChange
></input>

The checked radio button is styled with a static background color like this:

[type=radio]:checked + label {
 background-color: #eab308;
 border-radius: 8px;
}

Normally, I style my components using Tailwind CSS directly in my JSX file. However, for more complex styles, I use an external CSS file.

This is how I apply dynamic colors from the MongoDB data in my JSX:

const settingsstate = useSelector((state) => state.systemSettingsReducer);
const { settings } = settingsstate;

const bg = settings[0]?.color[0]?.bgColor;

<div className={`${bg}`}>

Is there a way to incorporate these dynamic colors into my external CSS file?

Answer №1

To change the style class based on a value, it is recommended to use the value that is being modified (in this case payment.value) as a parameter. You can achieve this by:

<input
 checked={settings[0]?.payments.length === 1 ? 'checked' : null}
 type='radio'
 id={payment.value}
 className = {`payment.value == some_thing ? className_true : className_false`}
 value={payment.value}
 onChange={
   settings[0]?.payments.length === 1
   ? setState(payment.value)
   : handleChange
/>

Answer №2

One possible solution is to utilize CSS variables:

<div style={{ "--backgroundColor": bgColor }}>Hello</div>

div {
  background-color: var(--backgroundColor);
}

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

Arranging an image and button within a column div row using Bootstrap

I'm encountering an issue with Bootstrap where I am trying to align the blue buttons neatly below the image. Link to the image: img Here is a visual representation: https://i.sstatic.net/tB5mU.png This is the code snippet: <div class="row&q ...

Unlocking the potential of a local mongoDB database in an Angular application without the need for a server - a truly client-side experience with the MAN stack

I have organized a mongoDB database with extensive data stored in multiple collections, all residing in a 'data' folder within the directory of my node app. I am now looking to develop a front-end interface for the database, including CRUD funct ...

Does setting white-space:nowrap enlarge the div?

My CSS code for div .name sets the width to 75% to truncate text if it doesn't fit. However, resizing the window causes the text to remain the same size and my entire website structure falls apart. This is the HTML code snippet: <tr> <t ...

What crucial element am I overlooking in the React Transition Group Component while implementing it for a carousel design?

I'm trying to add a feature to my Carousel where the opacity changes between images. When clicking on the icons, the images should transition smoothly. I've been using React Transition Group, but for some reason, it's not working as expected ...

What is the best way to access the value of an HTML tag in React?

Currently in the process of developing a feature for the price tab using React. These components are designed to allow users to add price classes to their shopping cart. One challenge I'm facing is how to retrieve the HTML string of an HTML tag. Here& ...

List of coordinates extracted from PolylineMeasure plugin in the React Leaflet library

I have 3 different scripts: 1. PolylineMeasure.jsx import { MapControl, withLeaflet } from "react-leaflet"; import * as L from "leaflet"; class PolylineMeasure extends MapControl { createLeafletElement() { return L.control.poly ...

Compound index in MongoDB is a type of index that consists

Currently, I am managing a Mongo DB collection that stores user information. One of the requirements is to ensure that both user_email and user_login fields are unique. To achieve this, I need to perform a check for uniqueness during the registration proce ...

What is the process for defining an outcome when a draggable element is placed into a droppable area using Jquery?

Currently, I am working on a task where I need to increase the value of a counter (var counter = 0;) every time a draggable image is dropped into a dropzone, which is also an image rather than a div. $( "#goldbag" ).draggable({ revert: "invalid", containm ...

The reducer is unable to assign null values to props

When logging in, I assign the token as 'randomTokenString' (I could also use the 'setToken' action to set the 'token' property). For logging out, I aim to assign null to the token. The issue arises when trying to set the toke ...

Correctly inputting MongoDB-specific collection methods which are currently defaulting to "any"

I'm facing an issue with typing Mongo collection method responses in my app. Specifically, I am having trouble finding a way to type the response of the deleteMany method. The documented response should look like this: { "acknowledged" : true, "delete ...

The text outside of the button is overridden by my CSS styling

I've been working on a simple card matching game and I decided to style the buttons to enhance their appearance. However, I'm facing an issue where the styling code has caused the text to appear outside of the button. Whenever I try to adjust the ...

What is the best way to showcase my products in a horizontal line? I am seeking a solution using PHP and Bootstrap to exhibit all the items retrieved

I am experiencing an issue with displaying the most recent events from my database using PHP. The Bootstrap framework and CSS are causing them to appear as a single column on the page, but I would like them to be displayed in rows of three. I have attempt ...

Bootstrap 5: Position the cards in close vertical alignment with one another

For my latest project, I have been working on creating a responsive card collection using Bootstrap 5 and Vue 3. By utilizing the container and row classes, I was able to ensure that all cards are aligned at the same level. However, in order to keep the ti ...

The animation does not reoccur in Firefox when using Modal

I have a unique issue with my modal that displays images, where the animation only works the first time on Firefox. When I open the modal for the first time, everything works perfectly, but if I close it and then reopen it, the animation no longer plays. I ...

Adjust the background color and transparency of a specific section using HTML

Is there a way to modify the background color or opacity of a specific area within an image? Take a look at my HTML, JavaScript, and CSS: function changeColor() { document.getElementById('testid').setAttribute("class", "style1"); } ...

How do I go about customizing the SpeedDialAction label with MUI v5?

I have a goal to customize our SpeedDial component in the following ways: Ensure that the labels (tooltips) are always visible Make sure the labels are wide enough to display the full text without wrapping To achieve the first part, I found out that sett ...

Ways to shorten text on mobile screens using CSS

Is it possible to use CSS to truncate text based on the current screen size or media queries? For example, consider this paragraph: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam porta tortor vitae nisl tincidunt varius. Lorem ipsum dolor ...

What is the equivalent of appendChild in React using vanilla js?

I've previously created this pen using vanilla JavaScript. Now, I'm looking to integrate it into my React component. displayPDF(url, canvasContainer, options) { options = options || { scale: 1 }; function showPage(page) { var view ...

Using jQuery to add a class to an image element when the source attribute contains a specific

I have a bunch of text that looks like this <div id="justThisDIV"><p>Some paragraph <img src="http://mydomain.com/image.jpg"/> </p> <p><img src="http://mydomain.com/wow.png"/></p> <p><img src="http://notm ...

Updated INNER header and footer - unrelated to the answered questions

After observing, the inner-header and inner-footer div scroll along with the area that contains the select list. How can I make that area scroll down while keeping the inner-header/footer fixed within the content? I hope my query is understandable. Thank ...