-1

I would like a text to be displayed on the screen and only be hidden when pressing a button, but I don't know how. I thought of using useState like this:

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

the problem I found is that when clicking on the button the page will be rendered again and the visibility value will be the default value (true). How can I do that?

  • 1
    According to that code when the state changes the value will be `false`. Are you able to provide an [mcve]? [Here's some documentation on how to create a React snippet](https://meta.stackoverflow.com/a/338538/1377002). – Andy Jan 31 '23 at 18:28

2 Answers2

1

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>
  );
}
Mirusky
  • 372
  • 3
  • 16
1
    const App(){
    
    const [isVisible, setIsVisible] = useState(false)
    
    return (
            <>
            {isVisible ? <label> This text will be shown on button click </label> : null 
   }
            <button onClick={()=>setIsVisible(true)}>click to show </button>
          
         </>
    )
    
    }
Ghias Ali
  • 257
  • 2
  • 10