Alejandro Alejandro - 3 months ago 16
React JSX Question

React-Redux - rank counter table

I am currently working on one of FCC's project, specifically to this one:

https://www.freecodecamp.com/challenges/build-a-camper-leaderboard

I was able to get it working just fine--I am able to click either recent or all-time scores and it will re-render the page accordingly.

The only thing I am missing is rendering the rank number appropriately. As of now, it is just current stack of number 1.

Here's my current code:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { recentData } from '../actions/index'
import { allTimeData } from '../actions/index'

export default class TableBoard extends Component {
constructor(props){
super(props);
}
componentDidMount() {
this.props.recentData() //fetch data most recent top
}
renderData(userData){
const name = userData.username;
const recent = userData.recent;
const allTime = userData.alltime;
let rank = 1;
return(
<tr key={name}>
<td>{rank}</td>
<td>{name}</td>
<td>{recent}</td>
<td>{allTime}</td>
</tr>
)
}
getRecentData(){
console.log('recent data')
this.props.recentData()
}
getAllTimeData(){
console.log('all-time data')
this.props.allTimeData();
}
render(){
return(
<table className="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Camper Name</th>
<th
onClick={this.getRecentData.bind(this)}
>Points in 30 days
</th>
<th
onClick={this.getAllTimeData.bind(this)}
>All-time Posts
</th>
</tr>
</thead>
<tbody>
{this.props.FCCData.map(this.renderData)}
</tbody>
</table>
)
}
}
function mapStateToProps(state){
return {
FCCData: state.collectData
}
}
function mapDispatchToProps(dispatch){
return bindActionCreators({ recentData, allTimeData }, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(TableBoard);


How can I add extra information into renderData function to display the rank correctly? I am assuming I need to an counter?

Answer

Pass index into map

 renderData(item,index){
    const name = item.username;
    const recent = item.recent;
    const allTime = item.alltime;
    return(
      <tr key={name}>
        <td>{index+1}</td>
        <td>{name}</td>
        <td>{recent}</td>
        <td>{allTime}</td>
      </tr>
    )
  }

Table Body

<tbody>
    {this.props.FCCData.map(this.renderData}
</tbody>