I am trying to follow a simple tutorials. My test code runs perfectly in my local server. But when I try to adapt the code to Plunker, it cause an error that I couldn't figure out why. The code runs fine in Snippet. Maybe I miss something. Plz help. :(
const Timer = ({currentValue}) => {
return(
<div className="Time">
{currentValue}
</div>
);
};
class App extends React.Component {
constructor(props){
super(props);
this.state = {currentValue: 150};
setInterval(
() => {
this.setState({currentValue: this.state.currentValue - 1});
}, 1000
);
}
// This cause an Unknown error in Plunker
resetTimer = () => {
this.setState({currentValue:150});
};
render() {
return (
<div className="App">
<Timer currentValue={this.state.currentValue} />
<button onClick={this.resetTimer}>Reset</button>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('example')
);
<!DOCTYPE html>
<html>
<head>
<script data-require="react@*" data-semver="15.2.0" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.0/react.min.js"></script>
<script data-require="react@*" data-semver="15.2.0" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.0/react-dom.min.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="example"></div>
<script src="script.js"></script>
</body>
</html>
Ur code is proper, don't know why it is not working on plunker
, same code is working on Jsfiddle
, you can try this alternative, bind the onClick
method manually, it will work, Try this:
const Timer = ({currentValue}) => {
return(
<div className="Time">
{currentValue}
</div>
);
};
class App extends React.Component {
constructor(props){
super(props);
this.state = {currentValue: 150};
setInterval(
() => {
this.setState({currentValue: this.state.currentValue - 1});
}, 1000
);
}
resetTimer(){
this.setState({currentValue:150});
};
render() {
return (
<div className="App">
<Timer currentValue={this.state.currentValue} />
<button onClick={this.resetTimer.bind(this)}>Reset</button>
</div>
);
}
}
Check the Working Code on-
plunker
code: https://plnkr.co/edit/NZPKuTdnIvL75IKgApFZ?p=preview
jsfiddle
: https://jsfiddle.net/ypt9q7p6/