LoginSignup
29
18

More than 5 years have passed since last update.

Reactで文字列内のURLをリンク(<a>タグ)にする方法

Last updated at Posted at 2017-04-19

TL;DR;

react-string-replace

  • npm i -S react-string-replaceする(もしくはyarn add -S react-string-replace)
  • react-string-replaceをimportもしくはrequireする
  • 正規表現でマッチした文字列を<a>タグで囲むだけ
  • 配列の文字列とかでももちろん問題なく動く

import reactStringReplace from "react-string-replace"して、
reactStringReplace(text, regExp, callback);とするだけ

以下サンプル

ListView.js
import React from "react";
import reactStringReplace from "react-string-replace";

const ItemList = ["https://www.google.com", "www.gentoo.org", "link to http://www.yahoo.com", "http://www.google.com"];
const regExp = /(https?:\/\/\S+)/g;

export default class ListView extends React.Component {
  render() {
    return (
      <div>
        <ul>
        {ItemList.map((item) => {
          return (
            <li>
              {reactStringReplace(item, regExp, (match, i) => (
                <a href={match}>{match}</a>
              ))}
            </li>
          )
        })}
        </ul>
      </div>
    )
  }
}

render関数が構築するDOMは以下のようになります。
ちゃんとマッチさせたい部分がリンクになっています。


<div>
  <ul>
    <li>
      <a href="https://www.google.com">https://www.google.com</a>
    </li>
    <li>
      www.gentoo.org
    </li>
    <li>
      link to <a href="http://www.yahoo.com">http://www.yahoo.com</a>
    </li>
    <li>
      <a href="http://www.google.com">http://www.google.com</a>
    </li>
  </ul>
</div>

以上になります。
もっといい方法とかあればご教授ください!

29
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
18