bier hier bier hier - 1 month ago 7
React JSX Question

How to pass in property into childcomponent?

I have a container that passes in an attribute called 'key' into the childcomponent:

import React, {PropTypes} from 'react'
import {connect} from 'react-redux'
import Pack from '../components/Pack/Pack'

const PacksContainer = ({Packs, addToCart}) => (
<div>
{Packs.map(pack =>
<Pack key={pack.id}/>
)}
</div>
)

const mapStateToProps = state => ({
Packs: [{id:1},{id:2}]
})

export default connect(
mapStateToProps
)(PacksContainer)


The childcomponent Pack looks like this:

import React, { PropTypes } from 'react'

const Pack = ({key}) => (
<div>
{key}
</div>
)

export default Pack


I was expecting the ids to display but there is nothing there? How can I display the ids from the parent?

Answer

If you'll try to access key prop, you'll get such a warning:

Warning: Pack: key is not a prop. Trying to access it will result in undefined being returned. If you need to access the same value within the child component, you should pass it as a different prop

key is something that is controlled by React internals before your component gets created. It will never be among the properties passed to a components from the considerations that one can accidentally overload it or use it for something unrelated.

A good practice is considered to pass down the identifier as another prop, even though it might look redundant.

const PacksContainer = ({Packs, addToCart}) => (
<div>
    {Packs.map(pack =>
        <Pack id={pack.id} key={pack.id}/>
    )}
</div>

)

const Pack = ({id}) => (
  <div>
    {id}
  </div>
)