Hi
Currently, I am into Chapter 8 “Dealing with State in React” in “Learning React” book, and I am trying the Lightning Strike Count code. Basically, the code below, creates a counter display that increments the counter by 100 every second using a SetTimer() function. Everything works fine. Now I added a “RESET” button that resets the counter when I press the button. I created a reset function in a component and I am trying to call that function from another component. This is not working. Can you please point out what I am doing wrong? Please take a look at the code section where I create the RESET button.
TIA
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> React1</title>
</head>
<body>
<div id="container"></div>
<script src="https://unpkg.com/react@15/dist/react.min.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
<script type="text/babel">
class LightningCounter extends React.Component{
constructor (props) {
super(props);
this.state = {
strikes:0
};
this.timerTick = this.timerTick.bind(this);
this.reset = this.reset.bind(this);
}
componentDidMount() {
setInterval(this.timerTick, 1000);
}
timerTick() {
this.setState ({
strikes:this.state.strikes + 100
});
}
static reset() {
this.setState({
strikes:0
});
}
render() {
var counterStyle = {
color: "#66FFFF",
fontSize: 50
}
var count = this.state.strikes.toLocaleString();
return (
<div>
<h1 style={counterStyle}>{count}</h1>
</div>
);
}
}
class LightningCounterDisplay extends React.Component {
reset() {
this.props.func();
}
render() {
var commonStyle = {
margin:0,
padding: 0,
};
var divStyle = {
width:250,
textAlign: "center",
backgroundColor: "#020202",
padding: 40,
fontFamily: "san-serif",
color: "#999999",
borderRadius: 10
};
var textStyle = {
emphasis: {
fontSize: 38,
...commonStyle
},
smallEmphasis: {
...commonStyle
},
small: {
fontSize: 17,
opacity: 0.5,
...commonStyle
}
};
return (
<div style = {divStyle}>
<LightningCounter/>
<h2 style={textStyle.smallEmphasis}>LIGHNTING STRIKES</h2>
<h2 style={textStyle.emphasis}>WORLDWIDE</h2>
<p style={textStyle.small}>(since you loaded this example) </p>
<!-- The RESET button is not working -->
<button onClick={LightningCounter.reset} > RESET</button>
<p></p>
</div>
)
}
}
var destination = document.querySelector("#container");
ReactDOM.render(<div>
<LightningCounterDisplay/>
</div>,
destination
)
</script>
</body>
</html>