Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React adding !important seems to break component re-rendering

Tags:

reactjs

I have a simple React component that accepts a prop that hides/shows a component's children. I hide/show using the style attribute and display: none. If I use display: none !important, the component no longer re-renders when it receives new props.

Within the render method, it looks like this:

var style = {};

if(shouldHide) {
    //this works
    style = {
        display: 'none'
    };
    //this does not
    //style = {
    //  display: 'none !important'
    //};
}

return (
    <span style={style} {...this.props} />
);

Here's the full example: https://jsfiddle.net/ccnokes/LnrnrLy2/ (relevant lines start at line 27)

What's going on here? Am I missing something?

like image 348
ccnokes Avatar asked Jul 05 '15 00:07

ccnokes


People also ask

How can I prevent unnecessary re-rendering in React?

1. Memoization using useMemo() and UseCallback() Hooks. Memoization enables your code to re-render components only if there's a change in the props. With this technique, developers can avoid unnecessary renderings and reduce the computational load in applications.

Why is my React component Rerendering?

React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.

How do you prevent components from Rerendering?

If you're using a React class component you can use the shouldComponentUpdate method or a React. PureComponent class extension to prevent a component from re-rendering.

How do you prevent components from rendering after state change?

React shouldComponentUpdate is a performance optimization method, and it tells React to avoid re-rendering a component, even if state or prop values may have changed. Only use this method if when a component will stay static or pure. The React shouldComponentUpdate method requires you to return a boolean value.


1 Answers

!important is currently unsupported - https://github.com/facebook/react/issues/1881

Does not appear they will be adding it any time soon.

They offer this as a workaround:

var sheet = document.createElement('style');
document.body.appendChild(sheet);
sheet.innerHTML = 'html {font-size: 1em !important;}';

But not sure if you want to go down that path or not.

I was able to resolve with a class switch:

//css
.hidden {display: none !important};
//jsx
var hideClass;

if(shouldHide) {
    hideClass = "hidden";
}

return (
    <span className={hideClass} {...this.props} />
);

Updated I went ahead and added the workaround above. And the fiddle here - https://jsfiddle.net/kellyjandrews/oan4grme/

Not exactly the answer you wanted, but it works :)

like image 128
Kelly J Andrews Avatar answered Sep 28 '22 04:09

Kelly J Andrews