Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,517 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.