Home > Enterprise >  Need help in conditional rendering in React
Need help in conditional rendering in React

Time:03-11

I'm trying to render a chart by populating data from a local JSON file. The initial render doesn't populate the array so I added a conditional rendering to the chart component. But I'm going wrong somewhere that after adding the condition the chart component doesn't render. Please correct me where I'm going wrong and help me to unblock this issue.

Screen grab of the empty array at the time of rendering

Corresponding code:

import BarChart from "./BarChart";
import { styled } from "@mui/material/styles";

import axios from "axios";

const drawerWidth = 340;
const open = true;

const Main = styled("main", { shouldForwardProp: (prop) => prop !== "open" })(
  ({ theme, open }) => ({
    flexGrow: 1,
    padding: theme.spacing(3),
    transition: theme.transitions.create("margin", {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
    marginLeft: `-${drawerWidth}px`,
    ...(open && {
      transition: theme.transitions.create("margin", {
        easing: theme.transitions.easing.easeOut,
        duration: theme.transitions.duration.enteringScreen,
      }),
      marginLeft: 0,
    }),
  })
);

const DrawerHeader = styled("div")(({ theme }) => ({
  display: "flex",
  alignItems: "center",
  padding: theme.spacing(0, 1),
  // necessary for content to be below app bar
  ...theme.mixins.toolbar,
  justifyContent: "flex-end",
}));

export function Test() {
  const [candidate, setCandidate] = useState([]);
  useEffect(() => {
    axios
      .get("./data.json")
      .then((res) => setCandidate(res.data))
      .catch((err) => console.log(err));
  }, []);
  
  //role
  let dataMap = new Map();
  let roleCategoriesArray = [];
  let roleCountArray = [];
  
  for (let attribute of candidate) {
    if (!dataMap.has(attribute.band)) {
      dataMap.set(attribute.band, 1);
    } else {
      dataMap.set(attribute.band, dataMap.get(attribute.band)   1);
    }
  }

  for (let [key, value] of dataMap) {
    roleCategoriesArray = [...roleCategoriesArray, key];
    roleCountArray = [...roleCountArray, value];
  }
  //spoc 

  dataMap = new Map();
  let spocCategoriesArray = [];
  let spocCountArray = [];
  for (let attribute of candidate) {
    if (!dataMap.has(attribute.spoc)) {
      dataMap.set(attribute.spoc, 1);
    } else {
      dataMap.set(attribute.spoc, dataMap.get(attribute.spoc)   1);
    }
  }

  for (let [key, value] of dataMap) {
    spocCategoriesArray = [...spocCategoriesArray, key];
    spocCountArray = [...spocCountArray, value];
  }

  const roleData = {
    count: roleCountArray,
    categories: roleCategoriesArray,
    titleText: "Role coverage",
    color: "#CB5757",
  };

  console.log(roleData);

  const spocData = {
    count: spocCountArray,
    categories: spocCategoriesArray,
    titleText: "SPOC",
    color: "#CF9152",
  };

  return (
    <Main open={open}>
      <DrawerHeader />
      <div style={{ marginTop: "100px", display: "flex", flexDirection: "row", flexWrap: "wrap",rowGap: "250px", coulmnGap:"100px"}}>
      {roleData.count>0 && <BarChart data={roleData} style={{ padding: "200px" }} />}
        <br />
        <hr />
        <br />
        {spocData.count>0 && <BarChart data={spocData} style={{ padding: "200px" }} />}   
      </div>
    </Main>
  );
}

CodePudding user response:

If you want to use the array length as a judgment basis, please try to fix roleData.count > 0 to roleData.count.length > 0.

...
return (
    <Main open={open}>
      <DrawerHeader />
      <div style={{ marginTop: "100px", display: "flex", flexDirection: "row", flexWrap: "wrap",rowGap: "250px", coulmnGap:"100px"}}>
      {/* ==== Here ==== */}
      {roleData.count.length > 0 && <BarChart data={roleData} style={{ padding: "200px" }} />}
        <br />
        <hr />
        <br />
        {/* ==== And Here ==== */}
        {spocData.count.length > 0 && <BarChart data={spocData} style={{ padding: "200px" }} />}   
      </div>
    </Main>
  );
  • Related