Using ReactJS to dynamically change styles based on state variables can sometimes cause CSS

Currently delving into the world of React.

Learning about states/props and the art of dynamically altering elements. I've set up the component states like this:

  constructor(props) {
    super(props);
    this.modifyStyle = this.modifyStyle.bind(this);
    this.state = {
      navigation: [
        { route: "/", title: "Home" },
        { route: "/about", title: "About Me" },
        { route: "/portfolio", title: "Portfolio" },
        { route: "/contact", title: "Contact" },
        { route: "/", title: "Services" },
      ],
      styling: "nav",
    };
  }

Focusing on the "Styling" state.

The purpose is to style the list element as seen here:

render() {
return (
  <div>
    <div className="trigram">
      <p>&#x2630;</p>
    </div>
    <ul className={this.state.styling}>
      {this.state.navigation.map((items) => (
        <NavItem route={items.route} title={items.title} />
      ))}
    </ul>
  </div>
);

The CSS for the "Styling" state is defined as follows:

   .nav {
  width: 100%;
  float: left;
  list-style: none;
  padding: 15px;
  transition: 1s;
   }

This setup, along with relevant li styling, yields the following result on the webpage:

[![Screenshot of menu][1]][1]

The objective is to adjust the list style to a smaller one upon a "Scroll" event using this function:

  componentDidMount() {
    document.addEventListener("scroll", this.modifyStyle, true);
  }
  modifyStyle = () => {
    this.setState({
      styling: "nav2",
    });
  };

The "nav2" style in question should mirror the main menu style but with reduced padding:

.nav2 {
  width: 100%;
  float: left;
  list-style: none;
  padding: 5px;
  transition: 1s;
}

Upon execution, everything seems to work fine initially. However, the updated styling ends up distorted and stuck in this shape:

[![screenshot issue][2]][2]

No clear explanation as to why this occurs persists, despite attempts made at debugging the CSS code. It appears that the Styling just refuses to cooperate in this particular scenario.

Suspecting it may involve how React handles states, although uncertain. Any insights would be highly valued.

TIA [1]: https://i.sstatic.net/bK1dt.png [2]: https://i.sstatic.net/w7Wh2.png

Answer â„–1

This wasn't related to React, but actually about CSS.

The problem was fixed by making the CSS for the "li" tag more general, rather than targeting a specific class.

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

Verify login availability using Javascript auto-check

For quite some time now, I've been grappling with a significant issue that has been consuming my attention. I am determined to implement an auto-check login availability feature in the registration form of my website. My goal is for it to verify the ...

Format the date using the Datepicker

I am looking to update the date format in my date picker from "12/25/2022" (for example) to "25/December/2022" Here is the code I have: $(".date-picker").datepicker({ format: 'dd-mm-yyyy', minDate: 0, numberOfMonths: \[3,1&b ...

Managing automatic page redirects in Ajax requests

For the past two days, I have been encountering a challenging issue with my Laravel application that is hosted on Heroku server. The app allows file uploads through an ajax request, displaying upload progress on the page and returning JSON response upon co ...

How to eliminate a div using jQuery

Within a repeater, there is a button that should remove the respective div followed by a database query using AJAX when clicked. The issue arises when attempting to remove the div in the success part of the AJAX call. Here is the code snippet: <asp:Up ...

Exploring the world of three.js, webGL, and GLSL through the magic of random

When using three.js to call a fragment shader, I have a shader that specifies a color for my material in rgb format. I am trying to figure out a way to multiply those colors by a random value. The code I currently have is as follows: gl_FragColor = vec4( ...

The response contains a JSON object with the values [object, Object]

I am attempting to showcase JSON data in an HTML table. Here is the code I have been using: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function(){ ...

What is the purpose of deserializing the user for every request using PassportJS?

While I have scoured the official documentation and various online resources, I am still unable to find a solution to what seems like an obvious question. When working with Passport.js, it is necessary to define two methods - one for serializing and one f ...

Stopping videos in the JQuery Cycle Plugin triggers the stop event

Currently, I have a simple cycle set up with YouTube videos using the following code: <script type="text/javascript"> $(document).ready(function () { $('#cycle').cycle({ fx: 'fade', sp ...

Vue: nesting components within components

Looking for a clever solution to create a nested component system with efficient rendering? Check out the code snippet below: custom-tab.vue (child component) <template> <slot></slot> </template> <script> export def ...

When an array object is modified in Vue, it will automatically trigger the get method to validate any

One of the challenges I am facing is related to a button component that has a specific structure: <template> <button class="o-chip border-radius" :class="{ 'background-color-blue': theValue.isSelected, ...

Retrieve the callback arguments using sinon.spy within a JavaScript promise

During my test with mocha and sinon, I encountered an issue where I couldn't retrieve a callback value from inside a promise scope of an HTTP-request due to the asynchronous nature of promises. It seems that by the time sinon.spy checks on the callbac ...

Unable to locate a type definition file for module 'vue-xxx'

I keep encountering an error whenever I attempt to add a 3rd party Vue.js library to my project: Could not find a declaration file for module 'vue-xxx' Libraries like 'vue-treeselect', 'vue-select', and 'vue-multiselect ...

Fatal error: zoid has obliterated all components inreactjs nextjs

I recently integrated PayPal into my Next.js application. Everything loads fine when I first visit the page, but if I navigate away and then back, it throws an error: unhandled_error: zoid destroyed all components↵ Unfortunately, PayPal does not provid ...

Error message: Uncaught TypeError - The function 'send' is not recognized in the Ajax new Request

When I called my ajax function, I encountered the following error: Uncaught TypeError: ajaxGetData.send is not a function Here is my code: <button onclick="myFunc()" class="btn btn-default">Click</button> <div id="getRes"></div> ...

What is the best way to ensure the main container fills the entire screen?

Given: Bootstrap 5.1 Visual Studio 2022 Professional Edition Blazor Server Application How do I modify the container to occupy the entire screen without any margins? <div class="container bg-primary"> Hello World! </div> Thi ...

Able to successfully access user account on Postman, however encountering login issues when trying to do

If I can successfully log in a user using Postman, does that indicate there is a bug in my front end code? Encountered CastError: Casting to string failed with value "{ email: '[email protected]', password: '123456' }" (type Objec ...

Incorporating mootools scripts into a gwt application

My issue involves creating an animation on a Composite that should start when data is loading. To test this, I created animations on regular divs using HTML: <div class="LoadDataWidget"> <div id="arrow" class="greenArrow"></div> < ...

Update search results when performing a new search on a web application (without using jQuery)

My simple web app interacts with an API to retrieve search results from a database and utilizes ajax to insert them into an empty ul element on the page (employing JSONP for cross-domain requests). I am struggling to achieve this functionality using plain ...

Is it possible to eliminate additional properties from an object using "as" in Typescript?

I am looking for a way to send an object through JSON that implements an interface, but also contains additional properties that I do not want to include. How can I filter out everything except the interface properties so that only a pure object is sent? ...

Is there a way to create a table cell that occupies zero space?

I have a very intricate table setup that resembles a tree structure, with only a few cells on the left and many on the right. I am looking to completely hide specific cells, along with their entire rows, using JavaScript based on their class. Using visibi ...