Skip to content

Instantly share code, notes, and snippets.

@balazimichal
Last active April 13, 2018 09:52
Show Gist options
  • Save balazimichal/be9fbb664b475f3ef84a56c92c61cd7b to your computer and use it in GitHub Desktop.
Save balazimichal/be9fbb664b475f3ef84a56c92c61cd7b to your computer and use it in GitHub Desktop.
React-playground-counting-cars
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class App extends React.Component {
constructor(props) {
super(props);
this.addCount = this.addCount.bind(this);
this.removeCar = this.removeCar.bind(this);
this.state = {
cars : [
{
'id' : 1,
'color' : 'red',
'count' : 0,
},
{
'id' : 2,
'color' : 'green',
'count' : 0,
},
{
'id' : 3,
'color' : 'blue',
'count' : 0,
}
]
}
}
addCount = (cars) => {
this.setState((currentState) => ({
cars : currentState.cars.filter((c) => {
if (c.id === car.id) {
return prevState.cars.count + 1
}
})
}))
}
removeCar = (cars) => {
this.setState((currentState) => ({
cars : currentState.cars.filter((c) => {
return c.id !== car.id
})
}))
}
render() {
return (
<div>
<h1>Counting cars</h1>
{this.state.cars.map((car) => {
return <p key={car.id}>{car.color} ({car.count}) <button onClick={this.addCount}>+</button><button onClick={this.removeCar}>-</button></p>
})}
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
</script>
<!--
Note: this page is a great way to try React but it's not suitable for production.
It slowly compiles JSX with Babel in the browser and uses a large development build of React.
To set up a production-ready React build environment, follow these instructions:
* https://reactjs.org/docs/add-react-to-a-new-app.html
* https://reactjs.org/docs/add-react-to-an-existing-app.html
You can also use React without JSX, in which case you can remove Babel:
* https://reactjs.org/docs/react-without-jsx.html
* https://reactjs.org/docs/cdn-links.html
-->
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment