user20276841
user20276841

Reputation:

how do i make a link using .map in react?

im trying to make a portfolio that renders my starred repos with links to the deployed page, using the github api. unfortunately the api dosent have a key for a deployed sites url. i tried using template literals but they seem to not be supported inside a react child. i even tried

href='https://chrispyrice024.github.io/'+ list.name +'/'

but i keep getting errors siting + as an unexpected token. heres what i have so far

import react from 'react';
import {useState, useEffect} from 'react'
import {BrowserRouter as Router, Link} from 'react-router-dom';

export default function Repos () {

     const [list, setList] = useState([])

     useEffect(() => {
        fetch('https://api.github.com/users/ChrispyRice024/starred?per_page=10').then(
        (response) => response.json()
    ).then(
        (data) => setList(data)
    )
     }, [])

return (
    <div>
        <h1>Top Repositories</h1>
        <ul>
    {list.map((list) => 
    
    <li><a href='https://chrispyrice024.github.io/'+ {list.name} +'/'> {list.name}</a></li>
    )}
    
        </ul>
    </div>
)

}

the list.name renders properly and i can link it to my repo using

href={list.html_url}

but for some reason i cant do that with the deployed url

Upvotes: 0

Views: 1621

Answers (1)

remonke
remonke

Reputation: 366

you can use template strings for this thing

<ul>
  {list.map((list) => 
    <li>
      <a href={`https://chrispyrice024.github.io/${list.name}/`}>
        {list.name}
      </a>
    </li>
   )}
</ul>

the reason your code isn't working is because you have wrap the whole string in curly braces and not the list.name because the syntax is valid

Upvotes: 1

Related Questions