data is not defined when using let in react

Viewed 19

I am trying to dynamically use data in my jsx, so when I use let to declare a variable called "data", and change its values in different cases, it says data is not defined during inspectation:TypeError: data is undefined.

I thought let basically allows us to do exactly this.....confused, any help please? which part did not work?

here is my code:

export default function Dashboard() {
  return (
    <div>
      <div className="flex p-5 gap-10">
        <Widgets type="user" />
        <Widgets type="order" />
        <Widgets type="earnings" />
        <Widgets type="balance" />
      </div>
    </div>
  );
}


import React from "react";
import { ArrowDownIcon, ArrowUpIcon } from "@heroicons/react/20/solid";
import {
  CursorArrowRaysIcon,
  EnvelopeOpenIcon,
  UsersIcon,
} from "@heroicons/react/24/outline";

function classNames(...classes) {
  return classes.filter(Boolean).join(" ");
}

const Widgets = ({ type }) => {
  let data;

  const amount = 100;
  const diff = 20;

  switch (type) {
    case "user":
      data = {
        title: "Userss",
        isMoney: false,
        link: "See all users",
        icon: <UsersIcon />,
      };
      break;
    case "order":
      data = {
        title: "Orders",
        isMoney: false,
        link: "View all orders",
        icon: <UsersIcon />,
      };
      break;
    case "earnings":
      data = {
        title: "Earnings",
        isMoney: true,
        link: "View all earnings",
        icon: <UsersIcon />,
      };
      break;
    case "user":
      data = {
        title: "Balance",
        isMoney: true,
        link: "See details",
        icon: <UsersIcon />,
      };
    default:
      break;
  }

  return (
    <div>
      <div className="flex flex-1 justify-between border-solid border-2">
        <div className="flex flex-col justify-between">
          <span className="title">{data.title}title</span>
          <span className="couter">
            {data.isMoney && "$"} {amount}
          </span>
          <span className="link">{data.link}</span>
        </div>

        <div className="right">
          <div className="percentage postive">
            <ArrowUpIcon />
            {diff}%
          </div>
          <div>{data.icon}</div>
        </div>
      </div>
    </div>
  );
};

export default Widgets;
1 Answers

I'm assuming you copy and pasted in your switch statement because you have a user case twice and no balance. Because your default doesn't set data to anything, it is undefined when type is 'balance'

Related