Home > Mobile >  Show and hide different div in reactjs
Show and hide different div in reactjs

Time:06-16

In react-js I have two div and two button, 1st button click fist div show and second button click second div show and 1st div hide

export default function Provider() {
 let firstClick = () => {
      const itemList = document.querySelector(".firstdiv");
      const itemList2 = document.querySelector(".Seconddiv");
      itemList.style.display = "block";
      itemList2.style.display = "none";
 }
 let secondClick = () => {
     const itemList = document.querySelector(".firstdiv");
      const itemList2 = document.querySelector(".Seconddiv");
      itemList.style.display = "none";
      itemList2.style.display = "block";
  }
  return (
    <div className="firstdiv">First Div Content</div>
    <div className="Seconddiv">Second Div Content</div>
    <button onClick={firstClick}>First Button</button>
    <button onClick={secondClick}>Second Button</button>
})

I use this method is use in react how to rewrite the code in react way, I am new in react and thanks in advance

CodePudding user response:

Using React you would go about this a bit different: instead of hiding components by css, you would render or not render components.

A compact example:

const SomeDiv = () => {
  const [showFirst, setShowFirst] = useState(true);
  // sets showFirst to not the value of showFirst and triggers a render  
  const toggle = () => setShowFirst(!showFirst); 

  return showFirst 
    ? <button onClick={toggle}>First</button> 
    : <button onClick={toggle}>Second</button>
}

CodePudding user response:

You can do something like that:

import { useState } from "react";

export default function HealthcareProvider() {
  const [hide, setHide] = useState(false);

  const toggleHide = () => {
    setHide(!hide);
  };

  return (
    <div>
      <div className="firstdiv" 
           style={{ display: hide ? "block" : "none" }}>
        First Div Content
      </div>
      <div className="Seconddiv" style={{ display: hide ? "none" : "block" }}>
        Second Div Content
      </div>
      <button onClick={toggleHide}>First Button</button>
      <button onClick={toggleHide}>Second Button</button>
    </div>
  );
}
  • Related