LoginSignup
3
0

More than 5 years have passed since last update.

reactで任意の回数分タグを生成してみる。

Posted at

今回やりたかったこと

reactで任意の回数分タグを生成したかった。

コード

import React from 'react';

class sample extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 4,
    };
  }

  render() {
    const arr = [];
    for (let i = 0; i < this.state.count; i += 1) {
      arr.push(<div key={i}>{i}</div>);
    }

    return (
      <div>
        {arr}
      </div>
    );
  }
}

export default sample;

解説

上記の例だとstateに数値4を持たせているが、ここは作るものにもよるがpropsから受け取った方が良さげ。

まず、stateに回したい回数分の数値を持たせる。

render内で
定数arrを作り、空の配列を用意しておく。

for分でstate.countの数値分回し、定数arrにpushしていく。(配列の末尾に追加していく)

あとはreturnの中で任意の場所に
定数arrを置いといてあげればreact側でいい感じにしてくれるみたいなので
そのままタグが回数分生成される。

3
0
2

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