0
1

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 1 year has passed since last update.

Reactの基礎3

Last updated at Posted at 2022-09-11

の続きです。

配列に対する操作

配列のメンバ関数mapに引数として関数を与えれば、配列の各要素に対してその処理をしてくれます。

index.js
const nums = [1,2,3,4,5];
const squares = nums.map(function(num) {
    return num*num;
});

console.log(squares);

const pokemon =  ["Bulbasaur", "Charmander", "Squirtle"];
const paragraphs = pokemon.map(mon => `<p>${mon}</p>`);

console.log(paragraphs);
[ 1, 4, 9, 16, 25 ]
[ '<p>Bulbasaur</p>', '<p>Charmander</p>', '<p>Squirtle</p>' ]

htmlに対する配列

まずは次のコードを実行してブラウザで観てみます。

index.js
import React from 'react';
import ReactDOM from 'react-dom/client';

function App(){
    const colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"];
    return (
        <div>{colors}</div>
    );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App/>);

出力:

image.png

このように要素がすべてつながって出てきてしまいます。これは各要素をhtml形式にすれば無事出力されます。

index.js
import React from 'react';
import ReactDOM from 'react-dom/client';

function App(){
    const colors = [
        <h3>Red</h3>, 
        <h3>Orange</h3>, 
        <h3>Yellow</h3>,
        <h3>Green</h3>,
        <h3>Blue</h3>,
        <h3>Indigo</h3>,
        <h3>Violet</h3>
    ]
    return (
        <div>{colors}</div>
    );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App/>);

出力:

image.png

配列に対する処理を使って

で紹介した迷子猫の掲示板のページは次のように書き換えることができます。

まず、4匹の猫のデータのオブジェクトを要素に持つ配列を作ります。

catData.js
const catData = [
    {
        img: "cat1.png",
        name: "Mr. Whiskerson",
        phone: "(212) 555-1234",
        email: "mr.whiskaz@catnap.meow"
    },
    {
        img: "cat2.png",
        name: "Fluffykins",
        phone: "(212) 555-2345",
        email: "fluff@me.com"

    },
    {
        img: "cat3.png",
        name: "Felix",
        phone: "(212) 555-4567",
        email: "thecat@hotmail.com"
    },
    {
        img: "cat4.png",
        name: "Pumpkin",
        phone: "(0800) CAT KING",
        email: "pumpkin@scrimba.com"
    }
]

export default catData;

これを読み込んでmap関数で各要素をhtml形式に変換して表示します。

index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './style.css';
import catData from './catData';

function Contact({img,name,phone,email}) {
    const catImgPath = require(`./images/${img}`);
    const phoneIconPath = require("./images/phone-icon.png");
    const emailIconPath = require("./images/mail-icon.png");

    return (
        <div className="contact-card">
            <img src={catImgPath} alt="cat"/>
            <h3>{name}</h3>
            {phone && <div className="info-group">
                <img src={phoneIconPath} alt="icon" />
                <p>({phone}</p>
            </div>}
            {email && <div className="info-group">
                <img src={emailIconPath} alt="icon"/>
                <p>{email}</p>
            </div>}
        </div>
    );
};

function App(){
    const contactElements = catData.map(cat => {
        return Contact(cat);
    });
    return (
        <div className="contacts">
            {contactElements}
        </div>
    );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App/>);

関数Appの中身がかなりスッキリしました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?