Should CSS variables be defined within the render method of a React component?

Yesterday, I mistakenly created and deleted a post. Now, I am facing an issue with creating a component that requires specific styling. The problem arises when the componentDidMount() method causes flickering during the rendering process, as it takes some time for the CSS to be applied.

I suspect that my component is resource-intensive, leading to a slight lag or delay in the execution of componentDidMount(). Therefore, I will only provide a snippet instead of a full demo, as the demo runs smoothly without any noticeable flickering.

To address this, I have tried integrating the value directly into the render method:

componentDidMount(){
   // CSS rendering causing flickering :/
}

render(){

    // Applying styles directly here returns the correct style instantly

    if (Math.round(window.scrollY + window.innerHeight +50) >= Math.round(document.body.scrollHeight)) {

            document.documentElement.style.setProperty('--background-transition', "")
            document.documentElement.style.setProperty('--is-page-bottom', "orange");
            document.documentElement.style.setProperty('--background-transition', "all 0.3s ease-out")
         }
             else{
                //setIsPageBottom_CSSVariable("rgba(84, 80, 79,0.85)")
                document.documentElement.style.setProperty('--background-transition', "")
                document.documentElement.style.setProperty('--is-page-bottom', "purple");
                document.documentElement.style.setProperty('--background-transition', "all 0.3s ease-out")
             }

After discussing with someone, they suggested using React Hooks to handle this issue, as componentDidMount proved ineffective due to the flickering before applying the background color.

As I am new to React Hooks, can I directly set properties like document.documentElement.style.setProperty within useEffect()? Would this align well with the design principle of React Hooks?

While exploring solutions, I came across advice from the official React documentation which states that:

The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it’s invoked, and it does not directly interact with the browser.

If you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead. Keeping render() pure makes components easier to think about.

Considering this guidance, would it be acceptable to handle my styling within componentDidMount despite it not being the best practice? Some suggest using addeventlistener, but this approach seems more suitable for different scenarios than the one I am currently facing.

In conclusion, what alternative approach would you recommend to prevent flickering when setting CSS properties in componentDidMount()? How does this relate to leveraging React Hooks effectively?

Answer β„–1

Learn how to implement useEffect in your code

//Replacing componentDidMount
useEffect(() => {
 //Place your code here
}, [])

Answer β„–2

For a more synchronous response to DOM changes, you might want to explore the benefits of useLayoutEffect. In cases where useEffect is not providing the desired results, consider switching to useLayoutEffect instead.

Answer β„–3

Avoid directly applying styles from React as it is not considered good practice. Instead, consider dynamically changing the class name based on the component's internal state using React.

You can achieve this by utilizing the useState hook to manage a 'loading state' and apply corresponding classes accordingly. This way, you can easily add or remove class names and associated styles without manually inserting them with JavaScript.

For a more organized approach, check out the classNames package at https://www.npmjs.com/package/classnames

Your CSS implementation would look like:

.additional-class {
background: red;
}

Remember that directly modifying the DOM in React goes against its principles. While there are ways to do so, it should be limited. Learn more about this topic here: https://reactjs.org/docs/refs-and-the-dom.html

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

Executing a PHP function every second using JS/Ajax: A step-by-step guide

Currently, I am utilizing the Highcharts API from http://www.highcharts.com/demo/dynamic-update to create a dynamic graph that reflects server load on my web panel. I have developed a PHP function called get_server_cpu_usage() which retrieves the current ...

Is there a way to preserve EXIF data when converting an image to base64?

I am currently facing an issue with reading a local image that has been created with a different exif.Orientation based on the degree of rotation. const exifData = piexif.load(data.toString("binary")); // Assign the desired orientation value ...

A guide on sending JavaScript variables to PHP using AJAX

I've been facing an issue while trying to pass the selected month from a select list in HTML using Ajax. Every time I select a month, it doesn't show up as expected. Initially, there's a placeholder "nothing" displayed due to the if-else con ...

Engaging with JSON data inputs

Need help! I'm attempting to fetch JSON data using AJAX and load it into a select control. However, the process seems to get stuck at "Downloading the recipes....". Any insights on what might be causing this issue? (Tried a few fixes but nothing has w ...

I need help with formatting a div to look like this

Looking to simplify my page by reducing the number of divs, wondering if this "tile" could be achieved without using one. Here's the example I have in mind: <a href="mks.html" class="big-tile big-tile-1"> <h1>town<br> libra ...

Should the text underneath the image be placed above the rest of the images?

In the process of developing my game, I encountered a challenge where text needs to be dragged under specific images. To achieve this, I envision creating tabs below the images for the text to be dragged onto. My initial approach involved wrapping each im ...

I can't seem to get the Font Awesome icons to display properly. What could be the issue?

How can I get Fontawesome icons to display properly in the footer? Despite having my CSS and HTML files in the same directory, the icons remain invisible. Additionally, the page seems to be loading slower than usual. I have provided all necessary informati ...

Removing a row from a React table using express and making an HTTP request with axios

I currently have a backend server running on localhost:3001 in conjunction with the frontend on localhost:3000. In my React application, I have set up a table and filled it with data fetched from the backend endpoint located at localhost:3001/food. My cur ...

Add elements to an array following an AJAX request

On my .cshtml page, I have the following script: $(function () { var tempArray = []; var tbValue = $('#tb1').val(); $.ajax({ url: "/ControllerName/getdata", dataType: 'json', ...

Using `reduce` in TypeScript, you can organize an array of objects based on a shared property

Here is an example of an array: [ { id: '1', task: 'Grocery shopping', isImportant: true }, { id: '2', task: 'Meeting', isImportant: false }, { id: '3', task: &apos ...

Personalized Bootstrap 4.1 Toggle Animation

I have been attempting to implement a customized menu toggle on Bootstrap 4.0's Navbar menu, using the code provided by Codeply HERE. My goal is to apply the X toggle style to my website's bootstrap navbar. Below is the current setup I have imple ...

Tips for effectively typing a collection of React wrappers in TypeScript

I encountered a situation in my team's application where we need the ability to dynamically compose component wrappers (HOCs) without prior knowledge of all the wrapper interfaces. This is mostly needed for swapping out context providers when renderin ...

Tips for adjusting the header color in materialize framework?

I've been working on a web template and I'm looking to customize the color displayed in the Android browser (maybe using JS?). The default color is blue. How can I go about changing it? https://i.sstatic.net/RxLbS.jpg Appreciate any help! ...

Node.js is indicating that the certificate has expired

When using Mikeal's request library (https://github.com/mikeal/request) to send an https request to a server, I keep encountering an authorization error of CERT_HAS_EXPIRED. request({ url: 'https://www.domain.com/api/endpoint', ...

What is the best way to send parameters to a callback function in a jQuery $.getJSON method?

Currently, I am attempting to utilize jQuery to access a custom API using Ajax/$.getJSON. In my code, I am trying to send a specific value to the Ajax callback method, but I am encountering an issue where this value is not being properly passed and instea ...

What methods does ReactJS employ to manage memory in applications with an abundance of components?

I am in the process of transforming a classic web application into ReactJS. I have implemented react-router to dynamically load various components, including child components, based on the current route. The app is expected to have a plethora of routes, an ...

Strangely glitchy navigation bar using jQuery

Over at this website, there's a top navbar that shrinks using jQuery when scrollTop exceeds 100px. The functionality works as intended, but there's an annoying stutter issue where the navbar starts jumping up and down erratically after slight scr ...

Removing the border from a button in CSS and HTML

Looking to build a sleek and stunning website, but struggling with removing button borders. Any help would be greatly appreciated! If you'd like to check out the issue, visit this link: https://i.sstatic.net/daaec.jpg. I'm aiming for no button o ...

Incorporating multiple true statements into an IF ELSE structure can enhance the decision-making

I'm struggling with getting a true return value for numbers that are integers and have either 4 or 6 digits - no decimals or letters allowed. The issue seems to be the validation of whether it's really a number and if it has a decimal point. Alt ...

Get the XML element containing the desired value in the downloadURL

Seeking assistance from experienced individuals regarding XML usage. Admitting to my lack of knowledge in this area, I am a beginner and seeking patience. I have successfully implemented code that loads marker data from a MySQL database and displays it on ...