Home > other >  Why style attr change can not trigger rerender in React?
Why style attr change can not trigger rerender in React?

Time:07-29

Why the display attr only change once when i click the button, it will not work afterwards

import React, { useState } from 'react';

function App() {
const [isShow, setIsShow] = useState(true);
const toggle = () => {
  setIsShow(!isShow);
  console.log(isShow);
}
return (
  <div>
    <button onClick={() => toggle()}>trigger</button>
    <span style={{display: isShow ? 'static' : 'none'}}>content area</span>
  </div>);
 }
export default App;

But,when i add key in the span, it can work. Why?

<span key={isShow} style={{display: isShow ? 'static' : 'none'}}>content area</span>

CodePudding user response:

There is no such property in display as static. You can either use block or inline based on your preference.

Here is a working demo: codesandbox

As to why adding key works, I think the reason is that React use key to find changes on the page and re-render it.

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity

Therefore, it might trigger a re-render by its diffing algorithm.

CodePudding user response:

That's because display: static is an invalid value, change it to something like block, or leave it undefined

<span style={{display: isShow ? undefined : 'none'}}>content area</span>

CodePudding user response:

The "static" is not the legal attribute of display, so when you want to set the attribue from 'none' to 'static' is will not work.

The code below should work fine.

<span style={{display: isShow ? 'unset' : 'none'}}>content area</span>
  • Related