Ways to update CSS attributes in a React component

Is there a way to dynamically change the width property of an element based on certain conditions?

<div className="consoleLayoutRoot-sideMenu">
        <ConsoleSideMenu />
 </div>

Here's the CSS code:

.consoleLayoutRoot-sideMenu .ant-menu {
  padding-top: 30px;
 
  /* background-color: #191146 !important; */
}

I've attempted to change the width using this method, but it doesn't seem to be working:

document.getElementsByClassName("conjnjnot-sideMenjnjbhbhu.annjn ").style.width = "77px";

Answer №1

  1. Declare a state variable

    const [selectedColor, setSelectedColor] = useState("#000000");
    
  2. Apply styling based on state

    const ColorComponent = () => {
      const [selectedColor, setSelectedColor] = useState("#000000");
      return (
        <div style={{backgroundColor: selectedColor}}>
        </div>
      );
    };
    

Updating the selectedColor state will dynamically change the background color of the div element.

Answer №2

It seems like the issue lies in treating a list as if it's an element. Handling this scenario is different in a React project.

In a React setup, you should trigger the component to re-render once the condition meets (potentially by modifying a state variable). While rendering the div, you can choose to include a style or a class name based on whether you want the width effect:

<div className={`consoleLayoutRoot-sideMenu ${shouldHaveWidthClass ? "width-class" : ""}`}>
        <ConsoleSideMenu />
</div>

The style definition for .width-class { width: 50px; } would be in your stylesheet.

Alternatively, inline styles could also be used, although they are generally discouraged:

<div className="consoleLayoutRoot-sideMenu" style={shouldHaveWidthSetting ? { width: "50px" } : undefined}>
        <ConsoleSideMenu />
</div>

Below is an example (employing a class approach):

const {useState} = React;

const ConsoleSideMenu = () => <span>x</span>;

const Example = () => {
    const [includeWidth, setIncludeWidth] = useState(false);
    
    const toggle = ({currentTarget: { checked }}) => {
        setIncludeWidth(checked);
    };
    
    return <React.Fragment>
        <div className={`consoleLayoutRoot-sideMenu ${includeWidth ? "width-class" : ""}`}>
                <ConsoleSideMenu />
        </div>
        <label>
            <input type="checkbox" onChange={toggle} checked={includeWidth} />
            Include width class
        </label>
    </React.Fragment>;
};

ReactDOM.render(<Example />, document.getElementById("root"));
.width-class {
    width: 50px;
}
.consoleLayoutRoot-sideMenu {
    border: 1px solid blue;
}
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

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

Issues with jQuery Ajax functionality in Rails application not achieving successful completion

When a card is moved onto another stack, an Ajax call is triggered twice. This only happens when there are multiple stacks. However, if the cards are rearranged within the same stack, the call is triggered only once. The Ajax call sends an array of IDs fo ...

Use jQuery to trigger a click event when an element is in focus, unless it was clicked to

I am currently developing a website using the MDL framework. One issue I encountered is that there is no default select form element provided. After some research, I found a solution by utilizing a menu component that displays when the input is clicked. Th ...

I'm curious if there is a method in c3 js that allows for displaying additional x-axis values when zooming in

Is it possible to dynamically increase the x-axis culling values with the c3.js data visualization tool when zooming in? This functionality is provided by d3.js. How can we implement this feature using c3.js? ...

Fetch file name using Ajax

I am struggling to retrieve the extension and name of a file using Ajax. This is my ajax code: $.ajax({ type: "POST", url: url, data: $("#updateMember").serialize(), mimeType: "multipart/form-data", contentType: false, cache: fal ...

Using the v-for directive in Vue.js 2 with a transition-group

I am working with a projects object that I populate after making an axios call. Then, I am using a v-for directive to loop through the projects object. Here is the code snippet: <ul class="row projects-list"> <li v-for="project in projects" ...

Mastering the Art of Content Swapping in SPA

Hey there! I'm in the process of creating a webpage using tornado io and incorporating various graphs. To add some single page app magic, I decided to swap out content within a div like so: <div id="chartType"> Chart goes here</div> <a ...

Error Message: "The component Connect(RenderPolygons) in React Redux is missing the required context variable "store"."

After encapsulating my entire app within a react-redux Provider and providing it with a store parameter, I was able to successfully use it from different parts of the app. However, after creating a hierarchy that includes components like Canva > RenderP ...

In ReactJS, it has been observed that the Checkbox consistently displays as true, but

I am facing a very specific issue. The checkbox with controlled component is functioning correctly on my local machine, but when I deploy the code online, it seems to have a problem. While everything else works fine (check/uncheck) and the data values are ...

Acquiring the console log data from Firefox version 43 using Selenium, all without the use of any

Can Selenium retrieve the console.log from browsers like Firefox 43? If so, how can it be done? My settings are as follows: DesiredCapabilities capabilities = DesiredCapabilities.firefox(); LoggingPreferences logs = new LoggingPreferences(); logs.enable( ...

Is there a way to dynamically create a Vue component for every tier of a nested JSON object without prior knowledge of the total number of tiers available?

I am working with JSON data that includes a list of retailers, some of which have subretailers that go multiple levels deep. My goal is to use Vue to generate markup that will show the parent retailer along with any nested subretailers underneath it, simi ...

Adjust the size of the <textarea> to match the height of the table cell

Below is the code I am using to generate a table containing an image along with a <textarea>: <table border="1" style="border-color: #a6a6a6" cellpadding="4" cellspacing="0" width="702">\ <col width="455"> <col width="230"> ...

What is the process for transforming an entire page into a docx file?

I am currently working on a project where I need to create a downloadable form. I am utilizing ReactJS to render an HTML page, and now I am looking for a solution to convert this page into a .docx file. Do you have any suggestions or ideas on how to achi ...

Library for JavaScript coding within a textarea element, complete with correct indentation

Seeking a JavaScript library for coding in a textarea with proper indentation. Came across Behave.js () which lacks the basic feature of indenting a new line based on the last lines indent. It only auto-indents by recognizing braces and parentheses. Codem ...

How to create a responsive image that appears over a button when hovering in Bootstrap?

My goal is to display an image over a button when hovering. I've tried adding the .img-responsive class in Bootstrap while including the image in the HTML, but it's not working as expected with my current method of loading images. The buttons the ...

The not:first-child selector targets all elements except for the first one in the sequence

This is a simple js gallery. I am using not:first-child to display only one photo when the page is loaded. However, it does not hide the other photos. You can view the gallery at this link: (please note that some photos are +18). My objective is to hide ...

The CSS override in Bootstrap 4 does not take effect unless it is placed within the <head> section of the HTML

After browsing through advice given on this Stack Overflow thread, I attempted to implement my own CSS solution: #bootstrap-override .carousel.slide { max-width: 1920px; min-width: 900px; overflow: hidden; margin ...

Updating new values with the function is not successful

I'm fairly new to JavaScript and I've encountered a problem. The issue is that the prompt in my code doesn't update with the correct values, while the 'console.log' function does for some reason. I'm really curious as to why t ...

Using an HTML5 image icon as an input placeholder

Is there a way to incorporate an image icon into an input placeholder and have it disappear when the user starts typing, across all browsers? In trying to achieve this, I successfully implemented a solution for webkit (Safari+Chrome) using ::-webkit-input ...

Accessing class properties from JavaScript code

Can you retrieve the class values of a style element using Vue's script section? For example: .node-output02 { bottom: #{-2+$portSize/-2}px; left: #{$nodeWidth/3}px; } In the script, I'd like to achieve: const left = .node-output02. ...

What is the most efficient way to gather all form inputs and then transmit them to an email address?

Could you please help me with creating a form page that collects user input data and sends it to my email? I am looking for solutions using only HTML, CSS, PHP, or JavaScript. Here is a preview of the page: Below is the PHP code snippet I've been wo ...