1

I am trying to redirect to the specified URL when clicked on image. It is appending localhost by default at the beginning of the URL and thus considering URL as the sub domain of localhost and its unreachable Approach 1:

<a rel="noopener noreferrer" href={rowData.preview} target="_blank">
   <Image
    className="preview-content"
    src={webAttachment}
   />
</a>

Approach 2:

<Link to={rowData.preview}>
    <Image
     className="preview-content"
     src={webAttachment}
    />
</Link>

{rowData.preview} includes url of any website. Not getting reliable solution in any of the approach.

3
  • If the specified URL is a react route you should use the second approach. If its an extrenal URL, the URL must be an absolute one. I mean, it should start with domain/url. Commented Nov 14, 2019 at 6:58
  • It is external URL eg: its is considering as localhost:3000/google.com Commented Nov 14, 2019 at 7:13
  • try to put the link directly into src without wrapping into rowData.preview and check if you are getting the desired result or not ? Commented Nov 14, 2019 at 7:17

4 Answers 4

2

Try these lines of code.

import { Link } from "react-router-dom";

<Link to="https://www.google.com/">
    <Image src="abc.jpg" className="imageLink" />
</Link>
Sign up to request clarification or add additional context in comments.

1 Comment

it will append localhost:3000/ at the beginning.
1
onClick={()=> window.open("someLink", "_blank")}

Visit the stackoverflow link.

Maintaining href "open in new tab" with an onClick handler in React

1 Comment

if my url is google.com then it is redirecting me properly. if it is just google.com the it is redirecting me to this localhost:3000/google.com.
1
  • href="google.com" will lead to "your-current-full-url/google.com".
  • href="/google.com" will lead to "your-domain/google.com".
  • href="https://google.com" will lead to "google.com".

Not just in react. even in normal html it works the same way. so make sure the external URL you are passing in rowData.preview has http://

2 Comments

how to handle when user enter "google.com" or "/google.com" or " https : // google.com" in href ? Any suggestions?
You may do userdata.replace(/([\s]+)/g,""); so that you won't have any spaces in entered URL. if(userdata.indexOf("/")==0){userdata=userdata.slice(1, userdata.length-1)};
0
<a target="_blank" href="https://www.linkedin.com/">
   <img
       src={b4}
       alt="Linkedin"
       className="mw3-ns"
       style={{height: "50px", width: "50px", cursor: "pointer"}}
                                
    />
 </a>

This worked for me. though I got a warning for using target="_blank"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.