LoginSignup
6
5

More than 3 years have passed since last update.

React TypeScript で Propsに HTMLタグを入れる方法

Last updated at Posted at 2020-01-16

Propsで渡すデータに改行タグを入れたかったので、
このように設定してみました。

import React from 'react';

// 型を定義する
type HeadlineType = {
  en: string | Array<string|JSX.Element>;
  ja: string;
}

// 子コンポーネント
const TheHeadline: React.FC<HeadlineType> = props => {
  return (
    <h1 className="headline">
      <div className="headline__en">{props.en}</div>
      <div className="headline__ja">{props.ja}</div>
    </h1>
  );
};

// 親コンポーネント
const App: React.FC = () => {
  return (
    <div id="app">
      <TheHeadline en={["Long Long", <br key="Some key" />, "Long Title"]} ja="長いタイトル" />
    </div>
  );
};

ポイントは、定義する型は、Element ではなく、JSX.Element ということ。
ここで時間かかってしまった。


[追記]
どうやら props で渡す引数にHTMLのタグがある場合、HTMLタグには任意のkey を指定しないと、
Warning: Each child in a list should have a unique "key" prop.
と警告が出るようです。


これでうまくいきました!

参考:https://stackoverflow.com/questions/33381029/react-how-to-pass-html-tags-in-props

6
5
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
6
5