Sachin
Sachin

Reputation: 2922

Add attribute in child element of dynamic HTML

I am getting HTML from server api and in that HTML I want to add target="_blank" to an anchor coming inside a div. I want to do that at front-end due to some restrictions, So please let me know how to do this.

I tried the following approach but I didn't like it as it is a SPA and it can have other elements with this class name.

  1. componentDidMount() { document.getElementsByClassName('download_div')[0] .getElementsByTagName('a')[0] .setAttribute('target', '_blank') }

  2. I can also use ReactDOM.findDOMNode(this). But accessing the DOM node and manipulating is against the React style. So I didn't go for it.

Upvotes: 1

Views: 1286

Answers (1)

stef
stef

Reputation: 14268

You could use a regular expression to find the element that needs the additional attribute and use dangerouslySetInnerHTML to output the results.

For instance:

componentDidMount() {
  const apiHtml = fetch('/my_api').then((apiHtml) => { 
    // fetch the raw HTML you want
    this.setState({apiHtml})
  })
}

render() {
  const rawHtml = this.state.apiHtml.replace('<a href', "<a target='_blank' href")
  return (
    <div>
      {this.state.apiHtml && <div dangerouslySetInnerHTML={{__html: rawHtml}} />}
    </div>

  )
}

Alternatively, a more complex approach would be to parse and transform the HTML string using react-html-parser

import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 } from 'react-html-parser';

function transform(node) {
  if (node.type === 'a' &&) {
    return convertNodeToElement(node, index, transform); // Alter the object here to suit your needs
  }
}

Upvotes: 2

Related Questions