JavaScript React Basics (retired) Thinking in Components Loops and Lists in JSX

Dennis Eitner
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Dennis Eitner
Full Stack JavaScript Techdegree Graduate 25,194 Points

How can you loop through lists if you have Application and Players in two seperate files?

I have the file

App.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Header from './components/Header.js';
import Player from './components/Player.js';
import logo from './logo.svg';
import './App.css';

class App extends Component {
    render() {
        return (
            <div className="scoreboard">
                <Header title="myScoreboard Title" />
                <div className="players">
                    <Player name={'tester'} score={121} />
                    <Player name={'John'} score={11} />
                </div>
            </div>
        );
    }
}

export default App;

and the file

Players.js
import React from 'react';
import PropTypes from 'prop-types';
import Counter from './Counter.js';


function Player(props) {
    return (
        <div className="player">
            <div className="player-name">{props.name}</div>
            <div className="player-score">
                <Counter score={props.score} />
            </div>
        </div>
    );
}

Player.propTypes = {
    name: PropTypes.string.isRequired,
    score: PropTypes.number.isRequired,
    players: PropTypes.arrayOf(
        PropTypes.shape({
            name: PropTypes.string.isRequired,
            score: PropTypes.number.isRequired
        })
    ).isRequired
};

export default Player;

1 Answer

Your list is essentially an array of children for a component, where each one gets run as a function. In this case, the function is the child Player component, and it outputs a particular set of HTML based on its props (arguments to the function).

The separation in different files just means the functions get passed around, exported and imported. That's just regular JavaScript going on, nothing too fancy.