edche
edche

Reputation: 680

How to hide/show a div in React?

I want to create a button to show and hide a div. In the first div (div1) I have a table and in the second div (div2) I have a chart. When a user clicks the button (with bar icon), should see the div2 (chart) and when the user clicks again it should return div1 (table). How can I do it?

tables.js

export function IncomeTables({firminfo, title, arr_number, financials, balance}) {
    ...
    ...

    return <Card>
    <div id="div1">
        <Table>
            <head>
               <tr>
                 <th colSpan="5">{title} <button style={{float:"right"}} className="btn btn-primary" ><FaChartBar/></button></th>
                 </tr>
                 ...
               </thead>
           ...
        </Table>
    </div>
    <div id="div2">
        <BarChart>
            ...
        </BarChart>
    </div>

    </Card>

Upvotes: 1

Views: 123

Answers (1)

Giorgi Moniava
Giorgi Moniava

Reputation: 28685

This is how you do it:

export default function App() {
  let [show, setShow] = React.useState(false);
  return (
    <div>
      {show ? <div>Hello</div> : <div>Another div</div>}
      <button
        onClick={() => {
          setShow(!show);
        }}
      >
        Click
      </button>
    </div>
  );
}

But when say instead of divs you render different types of components, when switching to another component, the previous one will be unmounted, and all state will be gone (due to reconciliation). In such cases you may want to store state in parent (e.g. App), so that state is not lost.

Or alternatively you may change display property of the div you want to show/hide, based on state variable; in that case state will not be lost, because you are not unmounting anything just changing a CSS property.

Upvotes: 3

Related Questions