Modify the conditions of a CSS file in Bootstrap using JavaScript

My project requires internationalization support for right-to-left languages like Arabic and Hebrew, so I need to modify some Bootstrap classes (such as col) to float right instead of left.

I am using create-react-app with babel/webpack and react-bootstrap.

Since importing conditionally is not possible, I have implemented a conditional require in my code:

if (language.isLanguageLTR()) {
    console.log("REQUIRE RTL CSS");
    require("./rtl.css");
}

While this setup works fine in development mode, I face an issue when building my application using create-react-app - the css file gets imported even if the condition evaluates to false.

Is there a way (which I believe exists!) to override specific css classes without resorting to inline styles or adding special classes everywhere I use bootstrap columns?

I suspect webpack behavior might be the culprit during deployment, but I don't fully understand why. Perhaps there is a better approach to conditionally overriding css.

Below is a snippet of my custom css for reference:

.App {
  direction: rtl;
}
.col-sm-1 {
  float: right;
}
.col-sm-2 {
  float: right;
}
...

Answer №1

After some investigation, I discovered that when using a conditional import/require in webpack, the file is always inserted to ensure it is available if needed. This caused an issue when importing a css file as it overrode existing styles. To solve this problem, I ended up defining the css styles using pure javascript (similar to this solution: ) and surprisingly, it worked well on Chrome, Internet Explorer, and Firefox. Although not the most aesthetically pleasing approach, it was effective and did the job. Ideally, I would prefer having the styles in a separate .css file, but for now, this solution suffices.

    var style = document.createElement("style");
    style.appendChild(document.createTextNode(""));
    document.head.appendChild(style);

    style.sheet.insertRule(".App { direction:rtl; }", 0);
    style.sheet.insertRule(
        ".col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7,  .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12  {float: right;}",
        1
    );`

Answer №2

In my opinion, the most efficient method to achieve your desired outcome is by implementing a float: right class that can be dynamically added using jQuery. Here is an example:

// CSS
.rtl {
    float: right !important;    
}

// Javascript
var isLTR = true;
function changeDirection( isLTR ) {
    $( '.col-sm-1, col-sm-2' ).addClass( 'rtl' );
}

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

Ensure that the child element completely fills the parent element while maintaining a padding around the edges

How can I create a child div that fills 100% of the parent's width and height, including padding? I've tried using box-sizing = border-box, but it isn't working. I also attempted adding the box-sizing property to all elements with *, but tha ...

What is the best way to connect specific nodes to the edge of a canvas in cytoscape and create perfectly straight lines?

In the center column of my article, I have two graphs created with cytoscape showing "ancestors" and "descendants" on the sides. I am interested in displaying the connections ("edges") from the articles in the final generation of "ancestors" to the articl ...

What steps should be taken to complete orders following the checkout.session.completed event triggered by Stripe?

Having an issue with Stripe's metadata object that has a limit of 500 characters. My checkout flow is operational, but the only constraint is the character limit for my cart. I need to include extras and customer notes in my cartItems object for each ...

Retrieve a CSV file from the server using Angular and JavaScript

How can a visitor download a CSV file from the server using Angular 7? Many websites suggest creating a CSV file dynamically from data and then using blob creation for downloading. However, I already have the CSV file on the server and want to directly do ...

JQuery does not operate on content that is fetched through ajax requests

I've been struggling with this issue for quite some time now and I just can't seem to figure out what I'm doing wrong. (I suspect it's related to the ajax response) I attempted to upload an image to the server using the uploadifive plu ...

What is the best way to align a logo in a log-in screen?

I am having an issue with centering the logo on my login form. The "signin" text is centered perfectly, but the logo always stays at the top left corner. I don't understand why the logo is not centered. If anyone has a solution to propose, I would gre ...

Transformation of JSON data from Array to Object

I have a JSON data structure that looks like this: { tag: 'new-tag', stream_subjects: [1, 2, 3] } My goal is to transform it into the following format: { tag: 'new-tag', stream_subjects: [ {subject_id: 1}, {subject_id ...

React state change is causing a functional component to not re-render

When attempting to map out a nested array from the data retrieved by an http request in a functional component, you may encounter a frustrating error: "TypeError: Cannot read property 'map' of undefined". Even though the state is updated correctl ...

Is there a way to initiate an Edge animation when an onclick event occurs?

I am interested in incorporating an interactive Adobe Edge animation that activates upon the click of a conventional HTML form button. Could you please guide me on how to achieve this? ...

Receive JSON data with camel-case in a Web API 2.0 using a model in pascal-case style

My attempt to execute a PUT call on my Web API involves configuring the WebApiConfig.cs file to send data back to my Web project in camel case format. config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesCont ...

The combination of NextJS and Firebase Auth using the GoogleAuthProvider is powerful

I am encountering challenges while trying to integrate firebase authentication with Google Provider in NextJS. I have set up the necessary environment variables and successfully established a connection with firebase. However, I keep running into an error ...

"Enhance Your Website Navigation with Bootstrap Navbar Links Extensions

I'm stuck on nesting a "navbar" in a Bootstrap row. The issue I'm facing is how to get the links to expand across the entire column. https://i.sstatic.net/9QbSN.png The code for this problem looks like: <div class="col-6 p-3 ...

Is it possible to alter objects through the use of jQuery.map?

I'm working with a key-value pair that looks like this: var classes = { red: 'Red', green: 'Green' }; Is there a way to add a specific value before each key in the pair? Can jQuery.map help with this task? The desired end result ...

jQuery fadeIn effect happening at rapid speed

I am currently working on integrating ajax with WordPress. After the ajax call is completed, I am successfully fading out a specific div slowly. However, when trying to fade in the new data using jQuery's fadeIn() method, I noticed that regardless of ...

Restrict the quantity of user responses with JavaScript

For this questionnaire, users are limited to selecting and ranking only 3 out of the 5 listed Social Apps. I am currently using questback to build the survey, but I require assistance in implementing a JavaScript condition. <table> <tr> & ...

Steps icons in the MUI Stepper component can be adjusted to remove the space between line connectors

I'm running into an issue while attempting to build a Stepper component using MUI V5. The problem I am facing is the presence of a gap between the icons and the line connectors. Here's what my current setup looks like: This is the desired outcom ...

Generating grid elements programmatically using the react-grid-layout package

Currently, I'm working on an application that combines Meteor and ReactJS. Utilizing the react-grid-layout component allows me to set up a grid layout for various items. However, the issue arises when I need to manually specify the position of each e ...

Difficulty creating a Service worker using sw-precache in a React application

After creating a react app using create-react-app, I realized I needed to modify the service worker code to suit my requirements. To achieve this, I am currently attempting to build the app using sw-precache. This tool is designed to aid in building a cus ...

Centralizing the Accordion header and expansion icon in React with Material-UI

I'm currently incorporating the Accordion feature from Material-UI library into my React project: My goal is to ensure that the accordion summary (header with "Accordion 1", "Accordion 2") is centered, and the expand icon (arrow) is also centered rig ...

Achieving JSON element sorting in the most effective way

https://i.stack.imgur.com/NQbdN.png Each array contains the following information: {{ id: 39, treaty_number: "qwe", insurant_name: "222", belonging_to_the_holding_company: "test", date_start: "2016-04-15", etc }} Is there a way to sort each array in asc ...