Recently I've started to learn Typescript, and figured out that all my knowledge about JavaScript is blown away, because of more watching how to code instead of just coding.
I am using React with TypeScript + TailwindCss
So my question is how do I can 'map' my array, which is on sepate file?
This is my component
import { AiFillShop } from 'react-icons/ai'
import { navUrl } from '../interfaces/navurl';
const Header = () => {
return (
<header className='w-full shadow-md fixed top-0 left-0 max-w'>
<div className='md:flex bg-purple-700 py-7 md:px-10 px-7'>
<div className="leftNav font-bold text-2xl cursor-pointer flex items-center font-[Poppins] ">
Super Shop
<span className='ml-2 cursor-pointer'>
<AiFillShop/>
</span>
</div>
<ul className="">
</ul>
</div>
</header>
);
};
export default Header;
I need to map next array into li elements
This is my Array
export const navUrl: { name: string; url: string }[] = [
{
name: 'HOME',
url: '/',
},
{
name: 'MISSION',
url: '/',
},
{
name: 'WARRANTY',
url: '/',
},
{
name: 'CONTACTS',
url: '/',
},
{
name: 'USED',
url: '/',
},
];
When I code this:
navUrl.map((link) => {
<li></li>
})
I have the error:
webpack compiled with 1 error and 1 warning ERROR in src/components/Header.tsx:19:40 TS1382: Unexpected token. Did you mean
{'>'}
or>
?
Assuming this should be in that <ul>
element, the only changes I'm seeing to be made are:
{}
.map()
callback (either explicitly with return
in a function body or implicitly as a single-expression arrow function)key
prop to the top-level element in the callback (ideally as a meaningful unique value from the array, such as an id
property or something)Minimal example:
<ul className="">
{ navUrl.map(link => <li key={link.name}></li>) }
</ul>
Or using values from the array elements:
<ul className="">
{ navUrl.map(link => <li key={link.name}>Name: {link.name}, URL: {link.url}</li>) }
</ul>
Or multiple lines in the return value (notice the parentheses that now wrap the <li>
JSX element):
<ul className="">
{ navUrl.map(link => (
<li key={link.name}>
Name: {link.name}, URL: {link.url}
</li>
)) }
</ul>
<li key={name}>