Home > other >  React Typescript mapping with an existing object
React Typescript mapping with an existing object

Time:06-08

using the below for dynamic side navigation rendering i have sidebarprops to clear a TS error below which i read was because the object for:

  const [routes, setRouting] = useState([])

was not defined

Property 'href' does not exist on type 'never'.ts(2339) 

when i setRouting i'm using a api file for data. when i use console.log(routes) comes back as an array of 8 - which is correct

Array(8)
0: {name: 'User List', href: '/people/users'}
1: {name: 'Basic Information', href: '#'}
2: {name: 'Permissions', href: '#'}
3: {name: 'Customers', href: '#'}
4: {name: 'Reports', href: '#'}
5: {name: 'Sales', href: '#'}
6: {name: 'Calendar', href: '#'}
7: {name: 'Alerts', href: '#'}

when i go to map it however i get route is undefined.

import {homeNavigations, userNavigations} from "@app/pages/api/breadcrumb-routing"

interface SidebarProps {
 links: {name: string, href: string}
 }

export default function Sidebar({links}: SidebarProps) {
const router = useRouter()
const x = router.pathname 
const [routes, setRouting] = useState([links])
const findLinks = () => { 
    debugger
    if (x.includes("people/users")){
        setRouting(userNavigations)
    }
    else setRouting(homeNavigations)
}
console.log(routes)

  useEffect(() => { 
    findLinks()
  },[]);

  return (
    <div className="hidden fixed w-28 bg-gray-700 overflow-y-auto md:block">
      <div className="w-full h-screen py-6 flex flex-col items-center">
            <div className="flex-1 mt-12 w-full px-2 space-y-1">
                {routes.map((route) => 
                    <Link href={route.href}>
                    <a
                    title={route.name}
                    className='text-white hover:bg-gray-800 hover:text-gray-300 group w- 
                    full p-3 rounded-md flex flex-col items-center text-xs font-medium'
                    >
                    <span className="mt-2">{route.name}</span>
                    </a></Link>
                )}
            </div>
        </div>
    </div>
)
}

imported data is this:

export const userNavigations = [
 {name: "User List", href: "/people/users"},
 {name: "Basic Information", href: "#"},
 {name: "Permissions", href: "#"},
 {name: "Customers", href: "#"},
 {name: "Reports", href: "#"},
 {name: "Sales", href: "#"},
 {name: "Calendar", href: "#"},
 {name: "Alerts", href: "#"} 
]

CodePudding user response:

try with const [routes, setRouting] = useState([...links]) and if the link are an array

interface SidebarProps {
 links: [{name: string, href: string}]
}

CodePudding user response:

If this is your code on your editor you have misspelled it. In map function you've passed routes as parameter when you should've called it as route.

  • Related