Home > OS >  Click button once click just render text
Click button once click just render text

Time:11-14

How to create a button than once click the button will render just text by using react hook

const WelcomeButton = (props) => {
  
const[welcomeBtn, setwelcomeBtn] = useState()

 const handelClick = () => {
 if() {
 retun <p>Hi John</p>
 }
}
  return (
  <div>
<button onClick={handelClick}> Welcome </button>    
  </div>
  )
  ;
};

CodePudding user response:

I suggest using a state that tracks that the button has been clicked, and update/toggle this value in the handleClick callback. Conditionally render either the button or the welcome text based on this state.

const WelcomeButton = (props) => {
  // initial state true to show button
  const [welcomeBtn, setWelcomeBtn] = React.useState(true);

  const handelClick = () => {
    // toggle false to hide button and display welcome message
    setWelcomeBtn(false);
  };

  return (
    <div>
      {welcomeBtn ? (
        <button onClick={handelClick}> Welcome </button>
      ) : (
        <p>Hi John</p>
      )}
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(
  <WelcomeButton />,
  rootElement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root" />
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related