Home > other >  Hide and show button in react
Hide and show button in react

Time:10-19

I have one div element and inside it have one button A. and there is button B outside which is hidden by default so when I click button A , the whole div should hide including button A and also it should display the hidden button B. And when I click the button B, it should open the div and and hide itself. How can I achieve this in reactjs. This is what I have tried but it is not showing any button on screen

import React from 'react'
import useState from 'react-dom'

const App = () => {
  const [show,setShow]=useState(true)
return(
  <>
  {show && <div>
  Hello
  <button>button A</button>
  </div>}
  
  <button onClick={()=>setShow(!show)}>button 2</button>
  </>
)

CodePudding user response:

Take a look at how this code is setting and using the show boolean state value for Button A and Button B.

const { useState } = React;

const App = () => {
  const [show, setShow] = useState(true)
  return (
    <div>
      {show && <div>
        Hello
        <button onClick={()=>setShow(!show)}>Button A</button>
      </div>}

      {!show &&
        <button onClick={()=>setShow(!show)}>
        Button B
        </button>
      }
    </div>
  );
}


// Render it
ReactDOM.render(
    <App />,
    document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

Note: Make sure you're importing useState from 'react' in your code. I had to write it as const {useState} = React; in order to get the above code snippet to work as expected.

CodePudding user response:

You can something like below

import React, { useState } from "react";

export default function ToogelButton({ children }) {

  // React state to manage visibility
  const [showButtonB, setShowButtonB] = useState(false);

  // function to toggle the boolean value
  function toggleShow() {
    setShowButtonB(!showButtonB);
  }
  
  if(showButtonB) {
    return (
        // Button B
        <button onClick={toggleShow}>BUTTON B</button>
      );
  }
  

  return (
    // Button A and content
    <div className="container">
      Test Content
      <button onClick={toggleShow}>BUTTON A</button>
    </div>
  );
}
  • Related