Trying to switch between local and public webpage while looping through data

Issue

At the moment, I am trying to list projects on a website in a grid. Some of them link to another page on the site and others link to another domain page. At the moment I am using React-Router’s ‘Link’ to go from one page to another, however this doesn’t work when going to a page outside of the domain. In the JSON file, I check for the ‘url’ variable which returns either the URL if its public or ‘project-page’ if it is local. I can’t figure out how to differentiate between the two in JSX; is there a work around while still utilizing the JSON file?

<div className="projects">
    {projectData.map((projectDetail, index) => {
        return(
            <div className='project-card'>
                <Link to={projectDetail.url}>
                    <img src={require('./images/icons/' + projectDetail.alt + '.jpg')} alt={projectDetail.title}/>
                    <h3>{projectDetail.title}</h3>
                    <p>{projectDetail.subtext}</p>
                </Link>
            </div>
        )
    })}
</div>

Solution

Well, to differentiate you can check the content of the projectDetail.url you are retrieving from that JSON in your javascript file, if that matches your domain (your website – having a project-page as you mention) or is it an external domain. You can also set a flag value in your json file. For each project set a value (e.g externalUrl: 1 or 0) and then check if projectDetail.externalUrl is 1 (it contains an external link). Then, maybe try the following for external domains:

<Link to={{ pathname: "external URL" }} target="_blank" />

In your case:

<Link to={{ pathname: projectDetail.url }} target="_blank" />

See this answer for detailed information: React-Router External link

Edit 1

If Link does not work for external websites, this would probably be related to the version of react-router you are using. Actually, to navigate to external websites you can as well use anchort tags <a> to redirect. Check what URL your project has and then conditional render a <Link> or <a>.

<a href="www.example.com" target=_blank></a>

Answered By – besjon_c

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.