Automatic Text Linking

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will work on creating an Automatic Text Linking component using React. The purpose of this lab is to learn how to use regular expressions to find URLs in a string and convert them into appropriate link elements. By the end of this lab, you will have a better understanding of how to automatically link URLs in text using React.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/conditional_render("`Conditional Rendering`") react/FundamentalsGroup -.-> react/list_keys("`Lists and Keys`") subgraph Lab Skills react/jsx -.-> lab-38341{{"`Automatic Text Linking`"}} react/conditional_render -.-> lab-38341{{"`Automatic Text Linking`"}} react/list_keys -.-> lab-38341{{"`Automatic Text Linking`"}} end

Automatic Text Linking

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

This component renders a string as plaintext, with URLs converted to appropriate link elements.

To achieve this, it uses String.prototype.split() and String.prototype.match() with a regular expression to find URLs in the given string. The matched URLs are then returned as <a> elements, dealing with missing protocol prefixes if necessary. The remaining parts of the string are rendered as plaintext.

Here is the code:

const AutoLink = ({ text }) => {
  const urlRegex =
    /((?:https?:\/\/)?(?:(?:[a-z0-9]?(?:[a-z0-9\-]{1,61}[a-z0-9])?\.[^\.|\s])+[a-z\.]*[a-z]+|(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})(?::\d{1,5})*[a-z0-9.,_\/~#&=;%+?\-\\(\\)]*)/gi;

  const renderText = () => {
    return text.split(urlRegex).map((word, index) => {
      const urlMatch = word.match(urlRegex);
      if (urlMatch) {
        const url = urlMatch[0];
        return (
          <a key={index} href={url.startsWith("http") ? url : `http://${url}`}>
            {url}
          </a>
        );
      }
      return <span key={index}>{word}</span>;
    });
  };

  return <div>{renderText()}</div>;
};

ReactDOM.createRoot(document.getElementById("root")).render(
  <AutoLink text="foo bar baz http://example.org bar" />
);

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Automatic Text Linking lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like