how to add target=_blank on react

Viewed 22619

I need to make all the links from a text open a new tab, and the text come from dangerouslySetInnerHTML={{__html: content,}}. the code is in a new class that extends component in react the block of code where i pick the text id in < section>

4 Answers

Here is my solution using replace

var content = `<a href="https://stackoverflow.com">Stack Overflow</a><a href="https://google.com">Google</a>`;

class App extends React.Component {

  render(){
    return (
      <div 
          dangerouslySetInnerHTML={{
              __html: content.replace(/href/g, "target='_blank' href")
          }}>
      </div>
    )
  } 
}
<Link to="route" target="_blank" onClick={(event) => {event.preventDefault(); window.open(this.makeHref("Your_route"));}} />

I Mean

<Link ... target="_blank">

OR

<a target='_blank' href={'Your_url'})}>Your Text</a>

You can use:

<Link to="route" target="_blank" onClick={(event) => {event.preventDefault(); window.open(this.makeHref("route"));}} />

Please refer to React-Router open Link in new tab

Related