Search code examples
javascripthtmlreactjshyperlinkhref

Making text urls clickable in a div


I'm trying to make url's clickable in my react application. My current approach is as follows.

render() {

  function urlify(text) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url) {
      return '<a href="' + url + '">' + '</a>';
    })
  }

  const headingAvailable = (
    <span className="home_post_text">{urlify(postData.heading)}</span>
  );

  return (
    <div className="home_post_sections sec2 unchange_div">{headingAvailable}</div>
  );
}

But i cannot get this to work correctly.

For example :

if my text is something like this

this is a good song https://www.youtube.com/watch?v=i9wBXC3aZ_I&index=8&list=RDxuAH21DkJow

My text is converted to something like this

this is a good song <a href="https://www.youtube.com/watch?v=i9wBXC3aZ_I&index=8&list=RDxuAH21DkJow"></a>

How can i fix this ?


Solution

  • React escapes html tags in strings by default, in order to prevent XSS security flaws.

    You need to return an a component, something like that:

    render() {
    
      function urlify(text) {
        const urlRegex = /(https?:\/\/[^\s]+)/g;
        return text.split(urlRegex)
           .map(part => {
              if(part.match(urlRegex)) {
                 return <a href={part}>{part}</a>;
              }
              return part;
           });
      }
    
      const headingAvailable = (
        <span className="home_post_text">{urlify(postData.heading)}</span>
      );
    
      return (
        <div className="home_post_sections sec2 unchange_div">{headingAvailable}</div>
      );
    }
    

    class Hello extends React.Component {
      constructor(props) {
        super(props);
        this.text = 'this is a good song https://www.youtube.com/watch?v=i9wBXC3aZ_I&index=8&list=RDxuAH21DkJow';
      }
    
      urlify(text) {
        const urlRegex = /(https?:\/\/[^\s]+)/g;
        return text.split(urlRegex)
          .map(part => {
            if (part.match(urlRegex)) {
              return <a href={part} key={part}> {part} </a>;
            }
            return part;
          });
      }
    
      render() {
        return <div> {this.urlify(this.text)} </div>;
      }
    }
    
    ReactDOM.render( <
      Hello name = "World" / > ,
      document.getElementById('container')
    );
    <script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
    <div id="container">
      <!-- This element's contents will be replaced with your component. -->
    </div>