Skip to content

Instantly share code, notes, and snippets.

@dranes
Created January 25, 2020 17:26
Show Gist options
  • Save dranes/38fb289befc28de88f33b1ac08df3de6 to your computer and use it in GitHub Desktop.
Save dranes/38fb289befc28de88f33b1ac08df3de6 to your computer and use it in GitHub Desktop.
React
<!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>
<!-- Don't use this in production: -->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
date: new Date(),
counter: 1,
comments: [
{id: 0, text: 'Hola'},
{id: 1, text: 'Hello'},
{id: 2, text: 'Chao'},
{id: 3, text: 'Bye'},
]
}
}
render() {
return (
<div>
<h1>Time is</h1>
<h2>{this.state.date.toLocaleTimeString()}</h2>
<h3>Incrementing: {this.state.counter}</h3>
<h3>Comments Section:</h3>
<ul>
{this.state.comments.map(comment => {
return <li key={comment.id}>{comment.text} <a href="#" onClick={this.removeComment.bind(this, comment)}>remove</a></li>;
})}
</ul>
</div>
);
}
tick() {
this.setState((state, props) => ({
date: new Date(),
counter: state.counter + 1
}));
}
removeComment = (comment, e) => {
e.preventDefault();
console.log("click", comment.id);
const comments = this.state.comments;
comments.splice(comments.indexOf(comment), 1);
this.setState({comments});
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
}
ReactDOM.render(
<Clock/>,
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.
Read this section for a production-ready setup with JSX:
https://reactjs.org/docs/add-react-to-a-website.html#add-jsx-to-a-project
In a larger project, you can use an integrated toolchain that includes JSX instead:
https://reactjs.org/docs/create-a-new-react-app.html
You can also use React without JSX, in which case you can remove Babel:
https://reactjs.org/docs/react-without-jsx.html
-->
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment