0
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?

【React】文字列を配列に変換して一文字ずつ表示する方法

Last updated at Posted at 2025-02-03

概要

React にて文字列を配列に変換して一文字ずつ表示する方法を紹介します。

背景

自社の忘年会に使うビンゴアプリを開発しています。
筆者は BE(TypeScript)、同期が FE(React)で分担してます。

FE のレビューをしていたら、ビンゴカードのヘッダーラベルを以下のような実装をしていました(同期は FE 初心者)

export default function App() {
  const headerChars = ["b", "i", "n", "g", "o"];
  return (
    <table border="1">
      <tr>
        {headerChars.map((char) => (
          <th>{char}</th>
        ))}
      </tr>
      /* 省略 */
    </table>
  );

今は bingo と少ない文字数ですが、何十文字にもなったら一文字ずつダブルクォーテーションで囲うことになります。
もう少しスマートに書けそうなので、僕なりに最適解を考えてみました。

同じような実装をしている方がいたら良い Tips になればと思い、その内容をご紹介します。

変更後のソース

export default function App() {
- const headerChars = ["b", "i", "n", "g", "o"];
+ const headerChars = "bingo";
  return (
    <table border="1">
      <tr>
-       {headerChars.map((char) => (
+       {[...headerChars].map((char) => (
          <th>{char}</th>
        ))}
      </tr>
    </table>
  );
}

解説

const headerChars = "bingo";

["b", "i", "n", "g", "o"] と定義していた部分を "bingo" に変更しました。

{[...headerChars].map((char) => (

スプレッド構文(...headerChars)を使って文字列を一文字ずつ展開し、配列に変換して map 関数でループするようにしています。

スプレッド構文が分からないよって方は以下をご参照ください!
JSのスプレッド構文を理解する

おわりに

ちょっとした変更でしたが、すっきり書けたと思います。
プログラムはいかに少ない労力で書けるかが大切です!
僕も皆さんも引き続きスマートなプログラムを書けるように精進していきましょう!
今回も見ていただきありがとうございました🙇‍♂️

0
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
0
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?