简体   繁体   中英

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>

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 div s 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 (eg App), so that state is not lost.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM