Skip to content

Instantly share code, notes, and snippets.

@emersonbrogadev
Last active August 31, 2019 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emersonbrogadev/de923ff7dc627ab19bd7dd4e716b97c6 to your computer and use it in GitHub Desktop.
Save emersonbrogadev/de923ff7dc627ab19bd7dd4e716b97c6 to your computer and use it in GitHub Desktop.

React Clock - uma demonstração do State e Lifecycle

DEMO 3

O conteúdo aqui apresentado é para exemplificar o funcionamento do State e Lifecycle do React.

Existe um video explicando passo a passo sobre o conteúdo desse repositório.

Esse código é apenas para fins educativos e foi formatado de forma a exemplificar conceitos.

Rodando o Projeto

Baixe o html abaixo e abra no browser.

Imagem do projeto rodando

React Clock

Se ainda não segue, conheça as nossas Redes Sociais

➜ Veja as dicas no Instagram

➜ Assita nosso canal no YouTube

➜ Curta nossa página no Facebook

➜ Não perca as atualizações no Twitter

➜ Veja os repositórios no Github

EmersonBroga.com
<!DOCTYPE html>
<html>
<head>
<title>State e Lifecycle - Clock - Demo 3</title>
<style type="text/css">
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#root {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
background: #005AA7;
background: -webkit-linear-gradient(to top, #FFFDE4, #005AA7);
background: linear-gradient(to top, #FFFDE4, #005AA7);
}
.clock {
width: 100%;
font-family: sans-serif;
font-size: 80px;
font-variant-numeric: tabular-nums;
color: #FFFFFF;
text-align: center;
}
</style>
</head>
<body>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date : new Date() };
}
componentDidMount() {
this.timerId = setInterval(
() => this.tick(),
1000);
}
componentWillUnmount() {
clearInterval(this.timerId);
}
tick() {
this.setState({
date: new Date(),
})
}
getTime() {
const { date } = this.state;
const h = `0${date.getHours()}`.slice(-2);
const m = `0${date.getMinutes()}`.slice(-2);
const s = `0${date.getSeconds()}`.slice(-2);
return `${h}:${m}:${s}`;
}
render() {
const time = this.getTime();
return (
<div className="clock">
It's {time}.
</div>
);
}
}
ReactDOM.render(<Clock />, document.getElementById('root'));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment