1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

react-admin: TextFieldで改行が表示されるようにする方法

Posted at

react-adminには、テキストを表示するコンポーネントにTextFieldがあります。この投稿では、TextFieldで表示するテキストに改行が入っていた場合、その改行を画面でも表示されるようにする方法を紹介します。

TextFieldで表示したテキストは改行が有効にならない

react-adminのTextFieldコンポーネントは複数行の表示を想定した作りになっていません。例えば、次のような改行入りテキストがあったとき、

line1
line2
line3

TextFieldコンポーネントで描画すると、

line1 line2 line3

のようになってしまいます。

改行テキストを描画する方法

TextFieldコンポーネントでは解決できないので、シンプルなカスタムコンポーネントを作ります。

改行を描画する中心的なテクニックとしては、CSSのwhite-space: pre-lineをテキストに適用する方法が手軽なので採用します。

カスタムコンポーネントのコードは次のようになります:

multilineTextField.tsx
import { FC } from "react";
import { TextField, TextFieldProps } from "react-admin";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  textContent: {
    whiteSpace: "pre-line",
  },
});

const MultilineTextField: FC<TextFieldProps> = (props) => {
  const classes = useStyles();
  return <TextField className={classes.textContent} {...props} />;
};

MultilineTextField.defaultProps = TextField.defaultProps;

export default MultilineTextField;

このMultilineTextFieldの使い方は、TextFieldと同じです。

<MultilineTextField source="note" />
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?