Reputation: 145
Say I have a class and I'm pulling in a props value
class Body extends React.Component {
render() {
var value = this.props.value;
This works fine, and I get the value I want (it's a string - I checked with the typeof function).
However, now I want to take a substring of the value:
class Body extends React.Component {
render() {
var value = this.props.value.substring(0,2);
I get an error saying Cannot read property 'substring' of null
Any ideas?
Upvotes: 0
Views: 8033
Reputation: 379
Check whether prop value null or not before substring
this.props.value && this.props.value.substring(0,2)
Upvotes: 0
Reputation: 10219
This is what you have default props for, just set your prop to an empty string as default.
getDefaultProps: function() {
return {
value: ''
};
}
Upvotes: 1
Reputation: 145
Thanks JordanHendrix, your post made me realize what's going on. If I just pass in a string through props, then the substring method works fine.
But in reality I have a ReactiveDict that pulls values, tracks changes on them, and passes them into props, and so when the page loads, a null object is initially passed in to my Body Class until it's updated to the correct value. This initial null value is what's causing the substring method to mess up, and so I need to put in a check for that.
Upvotes: 0