How to set target=_blank in React

How to set target=_blank in React

This article will help you understand how to set target=_blank in React with simple methods like using replace() method or adding an inline target attribute. Let’s go into detail now.

Set target=_blank in React

When you use the target=”_blank” tag, you first notice that when you click on a link or image using this tag, it will move that link to a new tab of the browser. The browser recognizes this tab as a new tab.

But only in some places you can use it because simply for the list of new articles you use like that will cause the visitor’s browser to open many new tabs and thus make the visitor no longer interested in the website. As a result, you will lose potential visitors.

Therefore, the target=”_blank” tag is often used to insert links and advertisements outside your website.

Code:

<a href="https://learnshareit.com/" target="_blank">Hosting & Domain</a>

Using the replace() method

The string.replace() method finds a substring or a regular expression in the string and replaces it with a value provided by the user.

With it, we can find the old href of the string containing the tag and will replace it with “_blank” and what we are looking for in the article.

Code:

import React from 'react';
 
var link = `<a href="https://learnshareit.com/">LearnShareIT home</a>`;
 
const App = () => {
  return (
    <>
    <h2>How to set target=_blank in React | LearnShareIT</h2>
    <div
          dangerouslySetInnerHTML={{
              __html: link.replace(/href/g, "target='_blank' href")
          }}>
      </div>
    </>
     
  );
};
 
export default App;

Output:

You can see that when we click on the link, the above url box will run to the target as a blank page before going to the destination link page.

Adding target inline attribute

And in this way, we will make it a bit simpler. We will change the property target directly to “_blank” by writing inline in the tag. Like other attributes, you must write the target attribute and add the value with “_blank” like the example below.

Code:

import React from 'react';
 
const App = () => {
  return (
    <>
    <h2>How to set target=_blank in React | LearnShareIT</h2>
    <br/>
    <a href="https://learnshareit.com/" target="_blank">LearnShareIT home</a>
    </>
     
  );
};
 
export default App;

The result is still the same as the above method, but this method will be more concise. Good luck with them.

Summary

Summarize, the article has shown you how to set target=_blank in React, but we recommend adding target inline attribute. If you have any problems, please comment below. We will answer as possible. Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *