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?
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.
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.
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.
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.
!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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With