Reputation: 785
I'm fairly new to the react side of life and have come across a slightly annoying issue with my Syntax that I could do with a little help on.
The premise is very simple:
I am trying to pass an object as a prop to a Component.
Parent Element: -- Trying to pass the state to the Totals component
class Dash_overview extends React.Component{
constructor(props){
super(props)
this.state = {
companies: {
title: 'companies on record',
value: null,
messurement: 'Companies'
},
earning: {
title: 'total earning',
value: null,
messurement: 'mill'
}
}
}
render(){
return (
<div className="overview-container">
<div className="totals">
<Totals values={this.state.companies}/>
<Totals values={this.state.earning}/>
</div>
</div>
)
}
}
Child Component -- which is going to use the values passed to it
class Totals extends React.Component{
constructor(props){
super(props)
this.state = {
}
}
render(){
return (
<div className="totals_comp">
<h3>{companies.title}</h3>
<h3>{companies.value}</h3>
<h3>{companies.messurement}</h3>
</div>
)
}
}
--
Im probably making a silly mistake but I have tried a few different variations of this without success so would really value someone pointing out where I am going wrong. :)
Thanks in advance, Wally
Upvotes: 0
Views: 1464
Reputation: 11
Since you are passing {title: 'companies on record',value: null,messurement: 'Companies'} as values prop, you should consume values from the other component. if you want to use companies name do this :
<div className="overview-container">
<div className="totals">
<Totals companies={this.state.companies}/>
<Totals companies={this.state.earning}/>
</div>
</div>
and then do this on Totals component:
const {companies}=this.props
render(){
return (
<div className="totals_comp">
<h3>{companies.title}</h3>
<h3>{companies.value}</h3>
<h3>{companies.messurement}</h3>
</div>
)}
Upvotes: 1
Reputation: 202608
You can spread the state values into the child component props, the object keys will be the prop names used within the component.
<Totals {...this.state.companies}/>
<Totals {...this.state.earning}/>
Or explicitly pass the prop values
const { messurement, title, value } = this.state.companies;
...
<Totals
messurement={messurement}
title={title}
value={value}
/>
<Totals
messurement={messurement}
title={title}
value={value}
/>
And then in the child access via props
<div className="totals_comp">
<h3>{this.props.title}</h3>
<h3>{this.props.value}</h3>
<h3>{this.props.messurement}</h3>
</div>
values={this.state.companies}
takes the state object value and assigns it to a prop named values
, but then in the child component you don't reference it at all. i.e. like props.values.title
.
Upvotes: 1
Reputation: 352
Try this.
const { title,value,messurement } = this.props.values;
render(){
return (
<div className="totals_comp">
<h3>{title}</h3>
<h3>{value}</h3>
<h3>{messurement}</h3>
</div>
)
}
Upvotes: 0