search

Home  >  Q&A  >  body text

How to use ReactJS to hide elements

I want to show a text on the screen and only hide it when a button is pressed, but I don't know how to do it. I want to use useState to achieve this effect:

const [textVisibility, setTextVisibility] = useState(true)
<button onClick={() => setTextVisibility(false)} />

The problem I found is that when the button is clicked, the page will re-render and the visibility value will change to the default value (true). what should I do?

P粉136356287P粉136356287445 days ago485

reply all(2)I'll reply

  • P粉579008412

    P粉5790084122023-09-08 10:05:34

    Idk what are you experiencing but for me it works fine the following code:

    import React from 'react';
    import {useState} from 'react';
    
    export function App(props) {
      const [textVisibility, setTextVisibility] = useState(true)
    
    
      return (
        <div className='App'>
          {textVisibility && <h1 onClick={() => setTextVisibility(!textVisibility)}>Hello React.</h1>}
          
          <button onClick={() => setTextVisibility(false)}>Invisible</button>
          <button onClick={() => setTextVisibility(true)}>Visible</button>
        </div>
      );
    }
    

    reply
    0
  • P粉155128211

    P粉1551282112023-09-08 00:20:36

    const App(){
        
        const [isVisible, setIsVisible] = useState(false)
        
        return (
                <>
                {isVisible ? <label> 点击按钮后将显示此文本 </label> : null 
       }
                <button onClick={()=>setIsVisible(true)}>点击显示</button>
              
             </>
        )
        
        }

    reply
    0
  • Cancelreply