I have the following in my App.js:
import { Box } from "@mui/system";
import Header from "./components/Header";
import ProjectList from "./components/ProjectList";
import CardLayout from "./components/CardLayout";
import React, { useState } from "react";
function App() {
const [view, setView] = useState("list");
const handleView = (event, newView) => {
setView(newView);
};
return (
<Box>
<Header view={view} onChange={handleView} />
<ProjectList />
<CardLayout />
</Box>
);
}
export default App;
The goal is to render only the ProjectList component when the toggle button with value list is selected <ToggleButton value={props.list}>
and render only CardLayout component when the toggle button with value grid is selected <ToggleButton value={props.grid}>
My Header.js component (button section) is this:
<ToggleButtonGroup
size="large"
value={props.view}
onChange={props.onChange}
exclusive
>
<ToggleButton value={props.list}>
<TableRowsIcon />
</ToggleButton>
<ToggleButton value={props.grid}>
<GridViewIcon />
</ToggleButton>
</ToggleButtonGroup>
Am I passing in the props from parent to child correctly? What should the setView
function be?
CodePudding user response:
You can simply use conditional rendering to achieve this.
For example, in your App.js
, change this:
<ProjectList />
to this:
{ view == list ?? <ProjectList /> }
That will render <ProjectList />
ONLY IF view == list
. You will need to create another state to handle the CardLayout rendering.
More information about conditional rendering can be found on the official docs: https://beta.reactjs.org/learn#conditional-rendering
CodePudding user response:
- I think instead this code
<ToggleButton value={props.list}>
you must write<ToggleButton value='List'>
because 'list' is value not property - if you use class components don't forget this. before props in the header component