Search code examples
reactjsreact-link

React opens website link after localhost url instead of https://websitelink


I get employers web addresses from a database, when I click web address text it opens as localhost:3000/webadresslink, how can I change it to https://webaddresslink

import React, { useState, useEffect } from 'react'
import EmployerService from '../../services/employerService'
import { Styles } from './style'
import { Card, Container } from 'react-bootstrap'

const EmployersList = () => {
  const [employers, setEmployers] = useState([])

  useEffect(() => {
    let employerService = new EmployerService()
    employerService.getAllEmployers().then(result => setEmployers(result.data.data))
  })
  return (
    <Styles>
      <Container>
        {
          employers.map(employer => (
            <Card>
              <Card.Body>
                <Card.Title>{employer.companyName}</Card.Title>
                <Card.Text>
                  <a href={employer.webAddress} target="blank">
                    {employer.webAddress}
                  </a>
                </Card.Text>
                <Card.Text>
                  {employer.email}
                </Card.Text>
                <Card.Text>
                  {employer.phoneNumber}
                </Card.Text>
              </Card.Body>
            </Card>
          ))
        }
      </Container>
    </Styles>
  )
}

Solution

  • Because kodlama.io isn't an absolute URL. It may intuitively look like one to you, but it isn't structurally any different from other relative URLs like:

    • index.html
    • index.com
    • index.html.com
    • www.index.html
    • etc.

    To tell the browser that this is a URL for a different host you'll need to prefix it:

    • https://kodlama.io

    Or even simply:

    • //kodlama.io

    If the data being displayed isn't well organized and some URL values have a prefix and some don't then a workable attempt at front-end logic could be simply: If the value doesn't contain "//" then prefix it with "//". For example:

    href={
      employer.webAddress.includes('//') ?
      employer.webAddress :
      `//${employer.webAddress}`
    }