Instantly share code, notes, and snippets.

Embed
What would you like to do?
React.js (ES6) Simple Counter
class App extends React.Component {
constructor(props) {
this.state = {
count: 0
}
}
onClick(e) {
this.setState({
count: this.state.count + 1
});
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.onClick.bind(this)}>Count Up!!</button>
</div>
)
}
}
React.render(
<App/>,
document.getElementById('app-container')
);
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>React Test</title>
<script src="http://fb.me/react-with-addons-0.13.0-rc1.min.js"></script>
<script src="http://fb.me/JSXTransformer-0.13.0-rc1.js"></script>
<script src="app.jsx" type="text/jsx;harmony=true"></script>
<head>
<body>
<div id="app-container"></div>
</body>
</html>
@julianguarinautoformax

This comment has been minimized.

Show comment
Hide comment
@julianguarinautoformax

julianguarinautoformax Feb 27, 2017

Why a state for a counter? This notion confuses me..... is this just a mere example, or states are used for variables heavily when doing code in JSX?

Why not a variable?

Thank you.

julianguarinautoformax commented Feb 27, 2017

Why a state for a counter? This notion confuses me..... is this just a mere example, or states are used for variables heavily when doing code in JSX?

Why not a variable?

Thank you.

@adeelibr

This comment has been minimized.

Show comment
Hide comment
@adeelibr

adeelibr Mar 10, 2017

@julianguarinautoformax because every time the counter value changes the UI has to be re-rendered to show the updated value of count.

adeelibr commented Mar 10, 2017

@julianguarinautoformax because every time the counter value changes the UI has to be re-rendered to show the updated value of count.

@leyaannie

This comment has been minimized.

Show comment
Hide comment
@leyaannie

leyaannie Mar 26, 2018

this program is not correct

leyaannie commented Mar 26, 2018

this program is not correct

@fanux365

This comment has been minimized.

Show comment
Hide comment
@fanux365

fanux365 Apr 14, 2018

https://reactjs.org/docs/state-and-lifecycle.html

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

fanux365 commented Apr 14, 2018

https://reactjs.org/docs/state-and-lifecycle.html

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment