Home > Net >  Passing array from parent to child component React
Passing array from parent to child component React

Time:07-14

I have an array teams and I want to be able to pass it to whichever components I want, right now that is Standings. Can anyone help me figure out why this isn't working? Thanks!

App.js

    function App() {
        return (
            <Router>
                <Navbar />
                <Routes>
                    <Route path="/" element={<Home />} />
                    <Route path="/teams" element={<Teams />} />
                    <Route path="/standings" element={<Standings teams={teams}/>} />
                </Routes>
            </Router>
        )

;
}

Standings.js

const Standings = () => {
    return (
        <div className='cont'>
            
            <table className='content-table'>
            <caption>American Football Federation Standings - Season 3</caption>
                <thead>
                    <tr>
                        <th>Rank</th>
                        <th>Team</th>
                        <th>W</th>
                        <th>L</th>
                        <th>Streak</th>
                        <th>PF</th>
                        <th>PA</th>
                        <th>P /-</th>
                    </tr>
                </thead>
                <tbody>
                    {this.teams.map((teams, i) => {
                        return (
                            <tr key={i}>
                                <td>{i 1}</td>
                                <td><img src={logo} width="30px"/>{teams.team}</td>
                                <td>{teams.wins}</td>
                                <td>{teams.loss}</td>
                                <td>{teams.streak}</td>
                                <td>{teams.pf}</td>
                                <td>{teams.pa}</td>
                                <td>{teams.pd}</td>
                            </tr>
                        );
                    })}
                </tbody>
            </table>
        </div>
    )
}

CodePudding user response:

In order to access teams that you included in <Standings teams={teams}/>, you have to tell the Standings component that it has to use the props given to it.

You can do it this way using the props keyword:

const Standings = (props) => {
   ...
   props.teams // This is how you access teams
   ...
}

Or by destructuring the props like this:

const Standings = ({teams}) => {
   ...
   teams // You can access teams directly
   ...    
}

CodePudding user response:

One more thing in addition, you are accessing teams using

{this.teams.map((teams, i) => return {} }

this here refers to window object, we use this inside class Components where this refers to the instance(object)

so change this line of code to ,

{teams.map((teams, i) => return {} }
  • Related