30-seconds-of-react React 30 seconds learning: Full Chinese translation, learning, address: 30-seconds-of-react-zh_cn-umi, all cases with analysis, annotation, online.

Series of articles:

  • React 30 seconds: Render array data into lists and tables
  • React 30 Seconds learning: Make input fields, password visibility, slider components, drop-down selectors, check box components
  • React 30 seconds: Create multi-line text components that limit the number of characters and words
  • React 30 seconds Speed learning: Implement collapsible, infinite hierarchy tree components
  • React 30 Seconds: Make text components that automatically recognize links
  • React 30 Seconds To Learn: Make accordion components
  • React 30 Seconds Learning: Create a multicast component
  • React 30 Seconds Quick Learning: Make folding panel components
  • React 30 Seconds: Create a countdown component
  • React 30 seconds Quick Learning: Create file drag and drop components
  • React 30 Seconds Speed Learning: Make modal box components
  • React 30 Seconds Learning: Create a star rating component
  • React 30 Seconds Learning: Make TAB components

AutoLink automatically recognizes links in text

Converts the URL in the string to the appropriate element.

  • Use regular expressions to matchString.prototype.split()String.prototype.match()To find the URL in the string.
  • Returns a<React.Fragment>No superfluous elements are produced; Its matching URL is rendered as<a>Element to handle missing protocol prefixes if necessaryhttp://And render the rest of the string as clear text.
import React from "react";
function AutoLink({ text }) {
  // The regular expression used to find the URL
  const delimiter = / ((? :https? : \ \ /)? (? : (? :[a-z0-9]? (? : [a - z0-9 \] {1, 21} [a - z0-9])? \.[^\.|\s])+[a-z\.]*[a-z]+|(? : 25 [0 to 5] | 2 [0 to 4] [0-9] | [01]? [0-9] [0-9]?) (? : \. (? : 25 [0 to 5] | 2 [0 to 4] [0-9] | [01]? [0-9] [0-9]?) () {3})? : : \ d {1, 5}) * [a - z0-9., _ \ / ~ # & =; % +? \ - \ \ (\ \)] / gi *);

  return (
    <React.Fragment>{/* Split into regular arrays, */} {text.split(delimiter).map(word => {// foo bar baz // http://example.org // bar console.log(word); Let match = word. Match (delimiter); if (match) { let url = match[0]; return (<a href={url.startsWith("http")?url : `http:/ / ${url} `}key={url} target="_blank">{url}</a>
          );
        }
        return word;
      })}
    </React.Fragment>
  );
}
Copy the code
example
export default function() {
  return <AutoLink text="foo bar baz http://example.org barhttp://baidu.com 123" />;
}
Copy the code
  • The sample code
  • Running effect