I'm trying to toggle a className value based on data received from Redux and passed to my components props. However with this code I am just receiving this error:
Uncaught TypeError: Cannot read property '0' of null
It looks to me that the props have not been received yet. I have heard about using default/fallback props but was not successful in implementing them.
How might I fix this?
calcROI() {
const myNum = (this.props.value1[0] + this.props.value2[0]);
let spanClassname = '';
if(myNum < 0) {
spanClassname = 'my-class';
}
const myNewNum = myNum.toFixed(0);
return {
spanClassname,
value : myNewNum
}
}
render() {
const {value3} = this.props;
const {spanClassname, value} = this.calcROI();
return (
<span className={spanClassname}>
My value is: {value + value3}
</span>
);
}
One solution is to use a default value, in this case is 0 add a few extra conditions when declaring myNum:
// check if this.props.value1 and value2 exists and their lengths > 1
const isMyNumExists = (this.props.value1 && this.props.value1.length > 1)
&& (this.props.value2 && this.props.value2.length > 1);
// if isMyNumExists is false or props is undefined, set myNum to 0
const myNum = this.props && isMyNumExists ?
(this.props.value1[0] + this.props.value2[0]) : 0;
UPDATED
If however, you want to set default props instead. You can do it by either using propTypes.defaultProps or setting the default props in mapStateToProps. The second case is only valid if you are getting value1 and value2 from the state, which I believe what you are doing. The default value of both examples is [0].
Using defaultProps:
// ... the rest of your import
import PropTypes from 'prop-types';
class MyClass extends Component {
// ... your code here
}
// insert default value here...
MyClass.defaultProps = {
value1: [0],
value2: [0]
};
Setting default value in mapStateToProps:
const mapDispatchToProps = (store) => ({
value1: store.value1 || [0],
value2: store.value2 || [0]
})