Home > database >  Switch between views in react.js
Switch between views in react.js

Time:02-28

I have this toggle button group in my Header.js component:

buttons

Here is the code:

<ToggleButtonGroup size="large">
            <ToggleButton>
              <TableRowsIcon />
            </ToggleButton>
            <ToggleButton>
              <GridViewIcon />
            </ToggleButton>
          </ToggleButtonGroup>

In the main App.js, I have two components: ProjectList (which is a table) and CardLayout (which is a grid) like this:

import { Box } from "@mui/system";
import Header from "./components/Header";
import ProjectList from "./components/ProjectList";
import CardLayout from "./components/CardLayout";    

function App() {
  return (
    <Box>
      <Header />
      <ProjectList />
      <CardLayout />
    </Box>
  );
}

export default App;

My goal is to render only the ProjectList when the left button is clicked and to render only CardLayout when the right button is clicked.

Essentially, I want to switch views depending on which button is clicked.

Do I need to use a hook for this? I'm new to react.js so I would appreciate any help. Thanks!

CodePudding user response:

You can try

import React, { useState } from "react";
import ReactDOM from "react-dom";

function App() {
  const [activepage, setactivepage] = useState(1);
  return (
    <>
      <h1>Change page!</h1>
      <button
        variant="contained"
        color="primary"
        onClick={() => {
          setactivepage(!activepage);
        }}
      >
        Change active page
      </button>
      {activepage ? <p>Page 1</p> : <p>Page 2</p>}
    </>
  );
}

ReactDOM.render(<App />, document.querySelector("#app"));

Edit funny-phoebe-tkdi54

CodePudding user response:

You can better refactor like this-

<SwitchBetweenLayout>
      <Layout layout={selectedLayout} />
</SwitchBetweenLayout>

The actual component like this -

function SwitchBetweenLayout() {
  const [layout, setLayout] = useState('listView');

  onClickButton(event) {
    const currentLayout = event.target.value; // gets 'listView or gridView
    setLayout(currentLayout); // only set if state is changed.
  }

  return (
    //HTML for 2 buttons with click handler

    <LayoutView layout={layout} /> 

  )
}

LayoutView would switch between the layout based on this prop

function LayoutView(props) { 
 const layout = props.layout;

 return(
    layout === 'gridView'? <GridView /> : <ListView />
 )
}
  • Related