menu

Questions & Answers

Need to 'map' my array, from separete file [React+ ts]

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 &gt;?

Answers(1) :

Assuming this should be in that <ul> element, the only changes I'm seeing to be made are:

  1. Wrap the "code" part in {}
  2. Return from the .map() callback (either explicitly with return in a function body or implicitly as a single-expression arrow function)
  3. Add a 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>
Comments:
2023-01-20 23:25:03
Didn't you forget about keys? Maybe use <li key={name}>
2023-01-20 23:25:03
@AgainPsychoX: Good catch, adding now...