Reputation: 994
I am writing my app with react.js and trying to get a data, which is an array of objects, from a component(P)'s child component(C1), then again pass the data to another child component(C2). However, when I console log the arrived data in (C2), it is weird that it shows the data is there, but when I console log its' property, it says it cannot read property of undefined. The code is below:
class ParentComponent extends Component {
constructor(props) {
super(props)
this.state = {
photos: []
}
}
myCallback = dataFromChild1 => {
this.setState({
photos: dataFromChild1
})
render(){
const { photos } = this.state;
return (
<main>
<Child1 callbackFromParent={this.myCallback} />
<Child2 photos={photos} />
</main>
)
}
class Child1 extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
const photos = [{width: '100px'}, {width: '150px'}];
this.props.callbackFromParent(photos);
}
render() {
return (
<main>
...
</main>
)
}
}
function Child2(props) {
const photos = props.photos;
console.log(photos) // > [{..},{..}]
console.log(photos[0].width) // > cannot read property 'width' of undefined
return (
<main>
...
</main>
)
}
Upvotes: 0
Views: 851
Reputation: 1770
Change your the Child2 function and test it.i hope the code is usefull for you
function Child2(props) {
const photos = props.photos;
console.log(photos) // > [{..},{..}]
if(photos.length){
console.log(photos[0].width)
}
return (
<main>
<p>Or you can use as the following </p>
<p>{photos.length? photos[0].width : '' }</p>
</main>
)
}
Upvotes: 1
Reputation: 1431
This fiddle is what you are searching.
Here's the code:
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
photos: []
}
}
myCallback = dataFromChild1 =>{
this.setState({
photos: dataFromChild1
});
};
render() {
const { photos } = this.state;
return (
<main>
<Child1 callbackFromParent={this.myCallback}/>
<Child2 photos={photos} />
</main>
);
}
}
class Child1 extends React.Component {
constructor(props) {
super(props)
}
componentDidMount() {
const photos = [{width: '100px'}, {width: '150px'}];
this.props.callbackFromParent(photos);
}
render() {
return (
<main>
...
</main>
)
}
}
function Child2(props) {
const photos = props.photos;
console.log(photos) // > [{..},{..}]
console.log(photos[0] ? photos[0].width : undefined) // > cannot read property 'width' of undefined
return (
<main>
...
</main>
)
}
ReactDOM.render(
<ParentComponent name="World" />,
document.getElementById('container')
);
The setState is async so in the first render your data array is empty.
Upvotes: 2
Reputation: 580
Try binding the callback function to the parent.
In the ParentComponent's constructor, write this:
this.myCallback = this.myCallBack.bind(this);
Upvotes: 0