Reputation:
I have a component right below which is later used inside another component in react.
Here is the code:
import React, { PropTypes } from 'react';
const MyComponent = () => (
<div>
<div className="row">
<div className="col-md-12">
<div className="media">
<div className="media-left media-middle">
<a href="#no"><img className="media-object" src={this.props.image} alt="" /></a>
</div>
<div className="media-body"><span className="pull-right">{this.props.name}</span>
<h4 className="media-heading">{this.props.title}</h4>
{this.props.desc}
</div>
</div>
</div>
</div>
</div>
);
MyComponent.propTypes = {
image: PropTypes.string,
name: PropTypes.string,
title: PropTypes.string,
desc: PropTypes.string,
};
export default MyComponent;
//Then on other component
import React from 'react';
import MyComponent from './mycomponent.component';
<MyComponent
title="Title Here"
name="Some Name"
desc="Description here"
image="http://placehold.it/100x100"
/>
The problem is that it's not rendering and the developer console is returning the following error:
"TypeError: undefined has no properties"
What is the problem here and how can I fix this issue?
Upvotes: 3
Views: 14093
Reputation: 2955
I faced the similar issue. This was caused because the initial array was defined as an empty array []
. This will make react to define it as undefined
which will cause the problem. Instead you can initialize the array with a random element and then replace it when you set state.
In my case I was using -
class App extends React.Component {
state = {
userdata:[], /* Notice that the array is empty*/
};
responseGoogle = (response) => {
console.log(response);
this.setState({userdata: response});
}
I changed it to
class App extends React.Component {
state = {
userdata:['Hello'], /* Notice that the array has an initial element*/
};
responseGoogle = (response) => {
console.log(response);
this.setState({userdata: response});
}
I am not really sure what the issue was but using an initial element solved the problem
Upvotes: 0
Reputation: 1489
You have to pass in props to MyComponent
like so:
const MyComponent = (props) => (
console.log("example prop is", props.image);
);
Upvotes: 6