Home > Software engineering >  What do I put as the type of the .map index so I can put it as an id?
What do I put as the type of the .map index so I can put it as an id?

Time:11-15

So I have an array of cities which I map to a react-router component (so I can redirect to the home page after the data for the city that is clicked is fetched). I put the .map index (index of the item in array) as an html id. This project was originally in JS but now I'm transforming it to TS. I get an error on id={i} which says: Type 'number' is not assignable to type 'string'. I understand what I have to do, but I have no idea how to do it. Where do I need to change the type so I can pass it properly?

const cities = city.map((town, i) => {
        return <Link 
        className={`citiy ${props.dark ? 'dark' : ''}`}
        to='/home' 
        onClick={handleFetch} 
        key={nanoid()} 
        id={i}>
            {town}
        </Link>
    })

CodePudding user response:

You can just cas it to string using string interpolation :

const cities = city.map((town, i) => {
    return <Link 
    className={`citiy ${props.dark ? 'dark' : ''}`}
    to='/home' 
    onClick={handleFetch} 
    key={nanoid()} 
    id={`${ i }`}>
        {town}
    </Link>
})

CodePudding user response:

You can just cast it to string

const cities = city.map((town, i) => {
        return <Link 
        className={`citiy ${props.dark ? 'dark' : ''}`}
        to='/home' 
        onClick={handleFetch} 
        key={String(id)} 
        id={String(i)}>
            {town}
        </Link>
    })
  • Related