I am just starting to learn ReactJS and I have encountered an error upon compilation of my code:
TypeError: Cannot read property 'value' of undefined
The error occurs on this line: count: this.props.value on the file counter.jsx
As you can see, I have tried to use console.log(this.props) on the render function on counter.jsx in order to validate if the props are set. They are set - so I do not know why I cannot access it in the state object in my Counter class.
Question: What am I doing wrong?
counter.jsx:
import React, { Component } from 'react';
class Counter extends Component {
state = {
count: this.props.value,
tags: []
};
render(){
console.log(this.props);
return (<React.Fragment>
<span>{this.formatCount()}</span>
</React.Fragment>
);
}
formatCount(){
var { count } = this.state;
return count === 0 ? <h1>Zero</h1> : count;
}
}
export default Counter;
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import 'bootstrap/dist/css/bootstrap.css';
import Counters from './components/counters';
ReactDOM.render(<Counters />, document.getElementById('root'));
registerServiceWorker();
counters.jsx:
import React, {Component} from 'react';
import Counter from './counter';
class Counters extends Component {
state = {
counters: [
{id: 1, value: 4},
{id: 2, value: 0},
{id: 3, value: 0},
{id: 4, value: 0},
]
};
render(){
return (
<div>
{this.state.counters.map(counter => (<Counter key={counter.id} value={counter.value} selected={true} />))}
</div>
);
}
}
export default Counters;