Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js how to pass in index as prop to child component from this.props array

New to React, so apologise in advance if my terminology is way off target. I have a table that has a list of people in specific order. I need to be able to create a this.props.tablePosition value based on the index on the person in question.

this.props is an array in the Table component. I have the code below thats not working as I'm not exactly sure how to get the index.

<RankingCards {...this.props} tablePosition={this.props.indexOf(this)} />
like image 595
ugotchi Avatar asked Nov 17 '22 06:11

ugotchi


1 Answers

Need to view rest of the code, but as per my understanding, you need this kind of flow, but correct me if I am wrong ;)


If you are getting the props like this, in the parent component

{
    tableData: [
        {name: "John", index: 1},
        {name: "David", index: 2},
        {name: "Ardhya", index: 3}
    ]
}

You can provide the required data to individual child components like this.

this.props.tableData.map(function(data){
    // do whatever processing you want to perform
    return(
        <RankingCards rawProp={data} tablePosition={data.index} key={data.index} />
    )
})

Inside your RankingCards component, you'll get the props other than key.

Eg. for first entity, if you print props with console.log(this.props), you'll get the values in this way.

{
    rawProp: {name: "John", index: 1},
    tablePosition: 1
}
like image 91
abhishake Avatar answered Jan 12 '23 00:01

abhishake