Last active
November 27, 2017 16:53
-
-
Save PepDevils/0f1e84476d1c1878b3dc3444e549dc4e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// REACT JS | |
// React's modular programming style | |
// create web components | |
// virtual-DOM é apenas uma representação em javascript puro (memória) do DOM | |
//JSX is a syntax extension for JavaScript: | |
const h1 = <h1>Hello world</h1>; | |
//need to instal a JSX compiler, to browsers read it | |
//pode ter atributtos | |
const p1 = <p id ="large">foo</p> | |
const p2 = <p id ="small">bar</p> | |
//nested elements, inside () | |
const theExample = (nested elements); | |
//like: | |
const theExample = ( | |
<a href="https://www.example.com"> | |
<h1> | |
Click me! | |
</h1> | |
</a> | |
); | |
//this code will NOT WORK | |
const paragraphs = ( | |
<p>I am a paragraph.</p> | |
<p>I, too, am a paragraph.</p> | |
); | |
//The first opening tag and the final closing tag of a JSX expression must belong to the same JSX element! | |
// Rendering JSX -- Rendering JSX -- Rendering JSX -- Rendering JSX -- Rendering JSX | |
//app.js | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
ReactDOM.render(<h1>Hello world</h1>, document.getElementById('app')); | |
//index.html | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<link rel="stylesheet" href="/styles.css"> | |
<title>Learn ReactJS</title> | |
</head> | |
<body> | |
<main id="app"></main> //valor que sera substituido pelo ReactDOm render | |
<script src="https://s3.amazonaws.com/codecademy-content/courses/React/react-course-bundle.min.js"></script> | |
<script src="/app.compiled.js"></script> | |
</body> | |
</html> | |
//outro exemplo, como passar variaveis para serem renderizadas, por exmplo uma lista | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
// Write code here: | |
const myList = ( | |
<ul> | |
<li>Learn React</li> | |
<li>Become a Developer</li> | |
</ul> | |
); | |
ReactDOM.render( | |
myList, //constante como atributo da função | |
document.getElementById('app') | |
); | |
//--/---///_//--/---///_//--/---///_//--/---/////--/---///_//--/---///_//--/---///_//--/ | |
// Advanced JSX -- Advanced JSX -- Advanced JSX -- Advanced JSX -- Advanced JSX -- Advanced JSX | |
//precisa sempre da tag para fechar, não é como o html, por exemplo <br> precisa de </br> | |
const profile = ( | |
<div> | |
<h1>I AM JENKINS</h1> | |
<img src="images/jenkins.png" > | |
<article> | |
I LIKE TO SIT | |
<br></br> | |
JENKINS IS MY NAME | |
<br></br> | |
THANKS HA LOT | |
</article> | |
</div> | |
); | |
//para fazer por exmplo calculos precisamos de parentes curvos | |
//este não calcula | |
ReactDOM.render( | |
<h1>2 + 3</h1>, | |
document.getElementById('app') | |
); | |
//este calcula | |
ReactDOM.render( | |
<h1>{2 + 3}</h1>, | |
document.getElementById('app') | |
); | |
// e este mostra a conta e tb calcula | |
const math = <h1>2 + 3 = {2 + 3}</h1>; | |
ReactDOM.render(math, document.getElementById('app') | |
); | |
// mais variaveis | |
const theBestString = 'tralalalala i am da best'; | |
ReactDOM.render(<h1>Hello, {name}!</h1>, document.getElementById('app')); | |
//rendirizar uma imagem, guardada numa variavel | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
const goose = 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-goose.jpg'; | |
const gooseImg = <img src={goose} />; | |
ReactDOM.render(gooseImg, document.getElementById('app')); | |
//Event Listeners | |
// o clique numa imagem que muda o src dessa imagem | |
function makeDoggy(e) { | |
e.target.setAttribute('src', 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-puppy.jpeg'); | |
e.target.setAttribute('alt', 'doggy'); | |
} | |
const kitty = ( | |
<img | |
src="https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-kitty.jpg" | |
alt="kitty" | |
onClick={makeDoggy}/> | |
); | |
ReactDOM.render(kitty, document.getElementById('app')); | |
// if else statment, best pratice | |
// este exemplo, atira a moeda ao ar para ver que imagem é renderizada | |
function coinToss() { | |
// This function will randomly return either 'heads' or 'tails'. | |
return Math.random() < 0.5 ? 'heads' : 'tails'; | |
} | |
const pics = { | |
kitty: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-kitty.jpg', | |
doggy: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-puppy.jpeg' | |
}; | |
let img; | |
// if/else statement begins here: | |
if (coinToss() === 'heads') { | |
img = ( | |
<img src={pics.kitty}/> | |
); | |
} else { | |
img = ( | |
<img src={pics.doggy}/> | |
); | |
} | |
ReactDOM.render( | |
img, | |
document.getElementById('app') | |
); | |
//operador ternario | |
//exemplo simples | |
const headline = (<h1>{ age >= drinkingAge ? 'Buy Drink' : 'Do Teen Stuff' }</h1>); | |
//para o exemplo da moeda assima | |
const img = <img src={pics[coinToss() === 'heads' ? 'kitty' : 'doggy']} />; | |
// uso do operador &&, muito comun em logica pra listas, exemplo: | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
const judgmental = Math.random() < 0.5; | |
const favoriteFoods = ( | |
<div> | |
<h1>My Favorite Foods</h1> | |
<ul> | |
<li>Sushi Burrito</li> | |
<li>Rhubarb Pie</li> | |
{!judgmental && <li>Nacho Cheez Straight Out The Jar</li>} //linha dinamica, depende de judgmental | |
<li>Broiled Grapefruit</li> | |
</ul> | |
</div> | |
); | |
ReactDOM.render( | |
favoriteFoods, | |
document.getElementById('app') | |
); | |
// using The array method .map() | |
// este usa um array e modifica cada um dos valores desse, e volta aguardar num array | |
//exemplo: | |
const strings = ['Home', 'Shop', 'About Me']; | |
const listItems = strings.map(string => <li>{string}</li>); //transforam simples strings, em elementos HTML para listagem | |
<ul>{listItems}</ul> | |
// in react list have to be keys, for internal memory tracking | |
// so to map a list well, this: | |
const peopleLis = people.map((person,i) => <li key={'person_' + i}>{person}</li>); //the have to be unique | |
//create a DOM element i react without JSX | |
// this: | |
const h1 = <h1>Hello world</h1>; | |
//become: | |
const h1 = React.createElement("h1",null,"Hello, world"); | |
//--/---///_//--/---///_//--/---///_//--/---/////--/---///_//--/---///_//--/---///_//--/ | |
// REACT COMPONENT -- REACT COMPONENT -- REACT COMPONENT -- REACT COMPONENT -- REACT COMPONENT | |
// render a simple component | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
class MyComponentClass extends React.Component { | |
render() { | |
return <h1>Hello world</h1>; | |
} | |
} | |
ReactDOM.render( | |
<MyComponentClass />, | |
document.getElementById('app') | |
); | |
//atributos num componente | |
//exemplo 1: | |
const redPanda = { | |
src: 'http://bit.ly/1U92LL3', | |
alt: 'Red Panda', | |
width: '200px' | |
}; | |
class RedPanda extends React.Component { | |
render() { | |
return ( | |
<div> | |
<h1>Cute Red Panda</h1> | |
<img | |
src={redPanda.src} | |
alt={redPanda.alt} | |
width={redPanda.width} /> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render( | |
<RedPanda />, | |
document.getElementById('app') | |
); | |
//exemplo 2: | |
const owl = { | |
title: "Excellent Owl", | |
src: "https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-owl.jpg" | |
}; | |
// Component class starts here: | |
class Owl extends React.Component { | |
render() { | |
return ( | |
<div> | |
<h1>{owl.title}</h1> | |
<img | |
src={owl.src} | |
alt={owl.title} | |
/> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render( | |
<Owl />, | |
document.getElementById('app') | |
); | |
//colocar logica dentro da função de renderizar | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
const friends = [ | |
{ | |
title: "Yummmmmmm", | |
src: "https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-monkeyweirdo.jpg" | |
}, | |
{ | |
title: "Hey Guys! Wait Up!", | |
src: "https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-earnestfrog.jpg" | |
}, | |
{ | |
title: "Yikes", | |
src: "https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-alpaca.jpg" | |
} | |
]; | |
// New component class starts here: | |
class Friend extends React.Component { | |
render() { | |
const friend = friends[0]; | |
return ( | |
<div> | |
<h1>{friend.title}</h1> | |
<img src={friend.src} /> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render( | |
<Friend />, | |
document.getElementById('app') | |
); | |
//usar um condicional | |
class TodaysPlan extends React.Component { | |
render() { | |
let task; | |
if (!apocalypse) { | |
task = 'learn React.js' | |
} else { | |
task = 'run around' | |
} | |
return <h1>Today I am going to {task}!</h1>; | |
} | |
} | |
//multiplas funções dentro do componente e ainda 'this': | |
class IceCreamGuy extends React.Component { | |
get food() { | |
return 'ice cream'; | |
} | |
render() { | |
return <h1>I like {this.food}.</h1>; //this.food referente a função interna | |
} | |
} | |
//use a eventlistener in a componenent | |
class MyClass extends React.Component { | |
myFunc() { | |
alert('Stop it. Stop hovering.'); | |
} | |
render() { | |
return ( | |
<div onHover={this.myFunc}> | |
</div> | |
); | |
} | |
} | |
//--/---///_//--/---///_//--/---///_//--/---/////--/---///_//--/---///_//--/---///_//--/ | |
// COMPONENTES RENDER OTHER COMPONENTES -- COMPONENTES RENDER OTHER COMPONENTES -- COMPONENTES RENDER OTHER COMPONENTES | |
//exemplo simples: | |
class OMG extends React.Component { | |
render() { | |
return <h1>Whooaa!</h1>; | |
} | |
} | |
class Crazy extends React.Component { | |
render() { | |
return <OMG />; | |
} | |
} | |
// este uso pode ser feito em diversos documentos, por exemplo varios componentes, um file para cada um | |
// depois um file geral para os renderizar, nota: ver os imports | |
// import, export pnecessário em ambos os files | |
//NavBar.js | |
import React from 'react'; | |
export class NavBar extends React.Component { | |
render() { | |
const pages = ['home', 'blog', 'pics', 'bio', 'art', 'shop', 'about', 'contact']; | |
const navLinks = pages.map(page => { | |
return ( | |
<a href={'/' + page}> | |
{page} | |
</a> | |
) | |
}); | |
return <nav>{navLinks}</nav>; | |
} | |
} | |
//ProfilePage.js | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
import { NavBar } from './NavBar.js'; | |
class ProfilePage extends React.Component { | |
render() { | |
return ( | |
<div> | |
<NavBar /> | |
<h1>All About Me!</h1> | |
<p>I like movies and blah blah blah blah blah</p> | |
<img src="https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-monkeyselfie.jpg" /> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render( | |
<ProfilePage />, | |
document.getElementById('app') | |
); | |
//--/---///_//--/---///_//--/---///_//--/---/////--/---///_//--/---///_//--/---///_//--/---///_//--/---///_//--/---/// | |
// COMPONENTS PROPS -- COMPONENTS PROPS -- COMPONENTS PROPS -- COMPONENTS PROPS -- COMPONENTS PROPS | |
// conseguir passar argumentos ao componente: | |
<MyComponent foo="bar" /> | |
//exemplo simples: | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
class Greeting extends React.Component { | |
render() { | |
return <h1>Hi there, {this.props.firstName}!</h1>; | |
} | |
} | |
ReactDOM.render( | |
<Greeting firstName='Groberta' />, | |
document.getElementById('app') | |
); | |
//como renderizar diferents ui dependendo de props diferentes | |
//app.js | |
import { Greeting } from './Greeting'; | |
... | |
<Greeting name="Alison" signedIn={true} /> | |
//or | |
<Greeting name="Alison" signedIn={false} /> | |
... | |
//Greeting.js | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
export class Greeting extends React.Component { | |
render() { | |
if (this.props.signedIn == false) { | |
return <h1>GO AWAY</h1>; | |
} else { | |
return <h1>Hi there, {this.props.name}!</h1>; | |
} | |
} | |
} | |
//event handler on a component | |
import React from 'react'; | |
class Example extends React.Component { | |
handleEvent() { | |
alert(`I am an event handler. | |
If you see this message, | |
then I have been called.`); | |
} | |
render() { | |
return ( | |
<h1 onClick={this.handleEvent}> | |
Hello world | |
</h1> | |
); | |
} | |
} | |
//passar o event handler para outro componente usar | |
//Talker.js | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
import { Button } from './Button'; | |
class Talker extends React.Component { | |
talk() { | |
let speech = ''; | |
for (let i = 0; i < 10000; i++) { | |
speech += 'blah '; | |
} | |
alert(speech); | |
} | |
render() { | |
return <Button talk={this.talk} />; | |
} | |
} | |
ReactDOM.render( | |
<Talker />, | |
document.getElementById('app') | |
); | |
//Button.js | |
import React from 'react'; | |
export class Button extends React.Component { | |
render() { | |
return ( | |
<button onClick={this.props.talk}> | |
Click me! | |
</button> | |
); | |
} | |
} | |
//modificar children props de um componente e repassalos modificados (acessar childrens) | |
//app.js | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
import { List } from './List'; | |
class App extends React.Component { | |
render() { | |
return ( | |
<div> | |
<List type='Living Musician'> | |
<li>Sachiko M</li> | |
<li>Harvey Sid Fisher</li> | |
</List> | |
<List type='Living Cat Musician'> | |
<li>Nora the Piano Cat</li> | |
</List> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render( | |
<App />, | |
document.getElementById('app') | |
); | |
//queremos acessar os li dentro do nosso custom component List, ver como: | |
//List.js | |
import React from 'react'; | |
export class List extends React.Component { | |
render() { | |
let titleText = `Favorite ${this.props.type}`; | |
if (this.props.children instanceof Array) { //logica se for mais do que 1 entao o titulo fica em plural | |
titleText += 's'; | |
} | |
return ( | |
<div> | |
<h1>{titleText}</h1> | |
<ul> | |
{this.props.children} //aqui que acessamos e voltamos a imprimir dentro de uma listagem | |
</ul> | |
</div> | |
); | |
} | |
} | |
//colocar valores default num componente | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
class Button extends React.Component { | |
render() { | |
return ( | |
<button> | |
{this.props.text} | |
</button> | |
); | |
} | |
} | |
// defaultProps goes here: | |
Button.defaultProps = { text: 'I am a button' }; //valor vai aparecer se <Button /> não tiver parametro text | |
ReactDOM.render( | |
<Button />, | |
document.getElementById('app') | |
); | |
//para fazer override do valor default basta parametrizar o componente | |
ReactDOM.render( | |
<Button text="Bla Bla button"/>, | |
document.getElementById('app') | |
); | |
//--/---///_//--/---///_//--/---///_//--/---/////--/---///_//--/---///_//--/---///_//--/---///_//--/ | |
// STATE -- STATE-- STATE-- STATE-- STATE-- STATE-- STATE-- STATE-- STATE-- STATE-- STATE | |
// Dynamic information - Nos componentes só os prop e state devem ser dinamicos, tudo o resto ser constante | |
// o estado deve ser passado no construtor como um objecto | |
// em react deve ser sempre chamado super do props | |
class Example extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { mood: 'decent' }; | |
} | |
render() { | |
return <div></div>; | |
} | |
} | |
//acessar o estado state de um component | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
class App extends React.Component { | |
// constructor method begins here: | |
constructor(props) { | |
super(props); | |
this.state = { title: 'Best App' }; | |
} | |
render() { | |
return ( | |
<h1> | |
{this.state.title} //acessso | |
</h1> | |
); | |
} | |
} | |
ReactDOM.render( | |
<App />, | |
document.getElementById('app') | |
); | |
//como fazer o update do estad state, com this.setstate | |
//por exemplo mudar a cor de um background de um div com um botao | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
const green = '#39D1B4'; | |
const yellow = '#FFD712'; | |
class Toggle extends React.Component { | |
constructor(props){ | |
super(props); | |
this.state = { color: green }; | |
this.changeColor = this.changeColor.bind(this); | |
} | |
changeColor() { | |
const newColor = this.state.color == green ? yellow : green; | |
this.setState({ color: newColor }); | |
} | |
render() { | |
return ( | |
<div style={{background: this.state.color}}> | |
<h1> | |
Change my color | |
</h1> | |
<button onClick={this.changeColor}> | |
Change color | |
</button> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render(<Toggle />, document.getElementById('app')); | |
// a função this.setState é sempre precedidade da função render | |
//--/---///_//--/---///_//--/---///_//--/---/////--/---///_//--/---///_//--/---///_//--/---///_//--/ | |
//____________________________________________Inline Style Para React JS________________________________________________// | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
const styleMe = <h1 style={{background: 'lightblue', color: 'darkred'}}> | |
Please style me! I am so bland! | |
</h1>; | |
ReactDOM.render( | |
styleMe, | |
document.getElementById('app') | |
); | |
//____________________________________________Make A Style Object Variable____________________________________________// | |
import React from 'react'; | |
const styles = { | |
color: 'darkcyan', | |
background: 'mintcream' | |
}; | |
export class StyledClass extends React.Component { | |
render() { | |
return ( | |
<h1 style={styles}> | |
Hello world | |
</h1> | |
); | |
} | |
} | |
//__NOTAS: | |
//In regular JavaScript, style names are written in hyphenated-lowercase: | |
const styles = { | |
'margin-top': "20px", | |
'background-color': "green" | |
}; | |
//In React, those same names are instead written in camelCase: | |
const styles = { | |
marginTop: "20px", | |
backgroundColor: "green" | |
}; | |
//__________________________________________________________//__________________________________________________________// | |
//__________________________________________________________//__________________________________________________________// | |
//________________________Separate Container Components From Presentational Components________________________// | |
//components/GuineaPigs.js | |
import React from 'react'; | |
export class GuineaPigs extends React.Component { | |
render() { | |
const src = this.props.src; | |
return ( | |
<div> | |
<h1>Cute Guinea Pigs</h1> | |
<img src={src} /> | |
</div> | |
); | |
} | |
} | |
//containers/GuineaPigsContainer.js | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
import {GuineaPigs} from '../components/GuineaPigs'; | |
const GUINEAPATHS = [ | |
'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-guineapig-1.jpg', | |
'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-guineapig-2.jpg', | |
'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-guineapig-3.jpg', | |
'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-guineapig-4.jpg' | |
]; | |
class GuineaPigsContainer extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { currentGP: 0 }; | |
this.interval = null; | |
this.nextGP = this.nextGP.bind(this); | |
} | |
nextGP() { | |
let current = this.state.currentGP; | |
let next = ++current % GUINEAPATHS.length; | |
this.setState({ currentGP: next }); | |
} | |
componentDidMount() { | |
this.interval = setInterval(this.nextGP, 5000); | |
} | |
componentWillUnmount() { | |
clearInterval(this.interval); | |
} | |
render() { | |
const src = GUINEAPATHS[this.state.currentGP]; | |
return <GuineaPigs src={src}/>; | |
} | |
} | |
ReactDOM.render( | |
<GuineaPigsContainer />, | |
document.getElementById('app') | |
); | |
//__________________________________________________________//__________________________________________________________// | |
//__________________________________________________________//__________________________________________________________// | |
//__________________________________________________Stateless Functional Components__________________________________________________// | |
// A component class written in the usual way: | |
export class MyComponentClass extends React.Component { | |
render() { | |
return <h1>Hello world</h1>; | |
} | |
} | |
// The same component class, written as a stateless functional component: | |
export const MyComponentClass = () => { | |
return <h1>Hello world</h1>; | |
} | |
// Works the same either way: | |
ReactDOM.render( | |
<MyComponentClass />, | |
document.getElementById('app') | |
); | |
//__________________________________________________________//__________________________________________________________// | |
//__________________________________________________________//__________________________________________________________// | |
//________________________________________________________PropTypes_____________________________________________________// | |
import React from 'react'; | |
export const GuineaPigs = (props) => { | |
let src = props.src; | |
return ( | |
<div> | |
<h1>Cute Guinea Pigs</h1> | |
<img src={src} /> | |
</div> | |
); | |
} | |
GuineaPigs.propTypes = { | |
src: React.PropTypes.string.isRequired //aqui prop types | |
}; | |
//__________________________________________________________//__________________________________________________________// | |
//__________________________________________________________//__________________________________________________________// | |
//_____________________________________________________REACT FORMS______________________________________________________// | |
//simple example | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
export class Input extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { userInput: '' }; | |
this.handleUserInput = this.handleUserInput.bind(this); | |
} | |
handleUserInput(e) { | |
this.setState({ | |
userInput: e.target.value | |
}); | |
} | |
render() { | |
return ( | |
<div> | |
<input type="text" value={this.state.userInput} onChange={this.handleUserInput}/> | |
<h1>{this.state.userInput}</h1> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render( | |
<Input />, | |
document.getElementById('app') | |
); | |
//__________________________________________________________//__________________________________________________________// | |
//__________________________________________________________//__________________________________________________________// | |
//______________________________________________Mounting Lifecycle Methods______________________________________________// | |
//There are three mounting lifecycle methods: | |
/* | |
componentWillMount | |
render | |
componentDidMount | |
*/ | |
// componentWillMount | |
// If you need to do something only the first time that a component renders, then it's probably a job for a mounting lifecycle metho | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
export class Flashy extends React.Component { | |
componentWillMount() { | |
alert('AND NOW, FOR THE FIRST TIME EVER... FLASHY!!!!'); | |
} | |
render() { | |
alert('Flashy is rendering!'); | |
return ( | |
<h1 style={{ color: this.props.color }}> | |
OOH LA LA LOOK AT ME I AM THE FLASHIEST | |
</h1> | |
); | |
} | |
} | |
ReactDOM.render( | |
<Flashy color='red' />, | |
document.getElementById('app') | |
); | |
setTimeout(() => { | |
ReactDOM.render( | |
<Flashy color='green' />, | |
document.getElementById('app') | |
); | |
}, 2000); | |
//componentDidMount | |
//When a component renders for the first time, componentDidMount gets called right after the HTML from render has finished loading | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
export class Flashy extends React.Component { | |
componentWillMount() { | |
alert('AND NOW, FOR THE FIRST TIME EVER... FLASHY!!!!'); | |
} | |
componentDidMount() { | |
alert('YOU JUST WITNESSED THE DEBUT OF... FLASHY!!!!!!!'); | |
} | |
render() { | |
alert('Flashy is rendering!'); | |
return ( | |
<h1 style={{ color: this.props.color }}> | |
OOH LA LA LOOK AT ME I AM THE FLASHIEST | |
</h1> | |
); | |
} | |
} | |
ReactDOM.render( | |
<Flashy color='red' />, | |
document.getElementById('app') | |
); | |
setTimeout(() => { | |
ReactDOM.render( | |
<Flashy color='green' />, | |
document.getElementById('app') | |
); | |
}, 2000); | |
//________________________________________Updating/Unmounting Lifecycle Methods______________________________________________// | |
//There are five updating lifecycle methods: | |
/* | |
componentWillReceiveProps | |
shouldComponentUpdate | |
componentWillUpdate | |
render | |
componentDidUpdate | |
*/ | |
//componentWillReceiveProps | |
//When a component instance updates, componentWillReceiveProps gets called before the rendering begins. | |
// componentWillReceiveProps will get called here: | |
ReactDOM.render( | |
<Example prop="myVal" />, | |
document.getElementById('app') | |
); | |
// componentWillReceiveProps will NOT get called here: | |
ReactDOM.render( | |
<Example />, | |
document.getElementById('app') | |
); | |
//componentWillReceiveProps automatically gets passed one argument: an object called nextProps. nextProps is a preview of the upcoming props object that the component is about to receive. | |
import React from 'react'; | |
export class Example extends React.Component { | |
componentWillReceiveProps(nextProps) { | |
alert("Check out the new props.text that " | |
+ "I'm about to get: " + nextProps.text); | |
} | |
render() { | |
return <h1>{this.props.text}</h1>; | |
} | |
} | |
// The first render won't trigger | |
// componentWillReceiveProps: | |
ReactDOM.render( | |
<Example text="Hello world" />, | |
document.getElementById('app') | |
); | |
// After the first render, | |
// subsequent renders will trigger | |
// componentWillReceiveProps: | |
setTimeout(() => { | |
ReactDOM.render( | |
<Example text="Hello world" />, | |
document.getElementById('app') | |
); | |
}, 1000); | |
//shouldComponentUpdate | |
//When a component updates, shouldComponentUpdate gets called after componentWillReceiveProps, but still before the rendering begins. | |
import React from 'react'; | |
export class Example extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { subtext: 'Put me in an <h2> please.' }; | |
} | |
shouldComponentUpdate(nextProps, nextState) { | |
if ((this.props.text == nextProps.text) && | |
(this.state.subtext == nextState.subtext)) { | |
alert("Props and state haven't changed, so I'm not gonna update!"); | |
return false; | |
} else { | |
alert("Okay fine I will update.") | |
return true; | |
} | |
} | |
render() { | |
return ( | |
<div> | |
<h1>{this.props.text}</h1> | |
<h2>{this.state.subtext}</h2> | |
</div> | |
); | |
} | |
} | |
// componentWillUpdate | |
//componentWillUpdate gets called in between shouldComponentUpdate and render | |
//componentDidUpdate | |
//When a component instance updates, componentDidUpdate gets called after any rendered HTML has finished loading | |
//componentWillUnmount | |
//componentWillUnmount gets called right before a component is removed from the DOM. If a component initiates any methods that require cleanup, then componentWillUnmount is where you should put that cleanup. | |
// | |
//__________________________________________________________//__________________________________________________________// | |
//__________________________________________________________//__________________________________________________________// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment