You are on page 1of 1
Components suport Reaet from “react Seport Resetao! fron ‘react-son! class Hello extends React, Component vender () ( return
ello (this. props.nan 3 Reset0oe.render(ell9 rane='John' />, a2) Use the Resets o eat naling. (orth ofc jbin) Children ‘this. praps.chaldren os Children ar passed asthe children property Defaults Setting default props Helis oereuleerane | color: “blue” See defautProps ‘Other components Functional components ‘Funetion tycamponent (mane }) roturn
“vase Use states (this. state to manage dynamic data 5 With Babel you can use proposals and getrid > of constuctor ‘As of React 162.0. fragments can be used to etn clase Hello extends component ( ‘ule chidren without adding extra wrapoing nodes = { usernane: undefined}: to the 0M, i srgort React, [ ‘onpanent concer Fragment 3 Fron *react* class Tnfo extends conponant( render () const { avatar, username ) = this.proos > ‘Nest componente separate concer ‘See: Composing Components Setting default state class Hello extends component ( constructor (prope) { haa eta (vanante: true ) Set the cofaut tate nthe conetructor() ‘And wthost constrictor using Babel wth props. class fl class Hello extends component { Pure components ‘Component API port React, (Purecomponent} from ‘react® ‘this. forceupdete() = eaatt this.cotstate( ... 9) . this satstate(state = (... )) ee one this. props Doesnt rerender if prop/tate hasn't changes. teers ‘ese methods ana properties ae avalible or Couponent instances. See Component API Updating Before rendering * _conponentOdupdetGrevPope rue, peat Use serstate() here but remember to compare props conponent Lilet () Dorit se this # shouldconponentipdaterenPap set) Spe render() frets fase render() fence render) ender conponentosahount() ‘ner rendering (DOW aval) # conpanantosaupdate (etops pe) (opeate onthe DOM nate componente vaune() Before DOM rem # TT ‘cau enors ie) Cobed when parents change properties an .setState(), These arent called fornia ‘etna the state on constructor), Ad DOM event handlers timers ft) on conponenttaahount(), ten cemeave thm on conpanentiLIUMOUtE) : Hooks (New) State Hook Snport React, ( useState } fran ‘react*: function example() { const (count, setcount] = usestato(0): vou clicked (count button onchick=[() oon Hooke ae naw acon in Bact 168, Ses Hooke at Glance Building your own hooks tunetion Frasnsstatue|propa) const [4sOnling, setIsOhtane usserfect(() = ( function handlestatuechango( status) ot eDelina(statu2z0n13n@) ? sotcount(ceunt + 3)) vusestato (mul); Declaring multiple state variables Fupetion Exanplacithvanystates() const [age setage] ~ useseato( 2) ‘count const [frust, aetFrait] = taState( "banana? fonat (t0gpe, aetTodes] - usestate({( text: ‘Learn Hooks! }))s Effect hook suport React, ( useState, usetffect } from *react* race eaepIEO, ‘onat (count, aetount] ~ usestete! fa mmr vsserrecti() 71 Update the document title using the browser APT secunont title ~ “You clickod S{count} tines"; ), feoane)) return ( 30 ‘vou clicked (count) tamesc/p> button onclick-{() => seteount(count + )}> clack we you fama with React clas ifsc methods you can think of uses ect Heal as conponantUishount, conpenen:DicUpdate and conponentvlunacunt combined ‘hatAPEcubscrbeToFrioniStatus{props.frisné.id, handleStatusthangs); return () > ( ‘ChatAPTunaubscribeFronfriendstatus(props.friend.d, handlestatusch, ? sf (asonline return ‘Losdano. ul ‘return asondine > ‘online ‘offline’ eee re ret ee eee ree function Frisndstatus(grops) { const dsonlsne af (sonine return 'Leséan ull) ( feturn Ss Ondine? ‘Online’ + ‘OFfIsne'; See Buln Your Own Hooks DOM nodes References class myconponent extends Component ( onder () ( input ref=(el => thie. input = el) /= sais conponentosatount () ( this. dnput.focus() Allows acces t9 00M nodes ‘Ses Ref andthe DOW - Other features Transferring props -vadeowlayer sre—"vaceo.ape class videoPlayer extonds Component ( ender () { ‘etun Propagate er * cow tote eub-component. See Wansering props - JSX patterns Style shorthand const style = { hoaght: 12 return «day stylen(style)> (ehoweopun 8 Popup />) Fragment - New features Returning multiple elements You can retum multiple elements a arays or fragment. onder 6) / vetura [ Sas kay (s0oFarat ater 1b Ai tey-"5"> second itons/1i 1 ? render () ( return ( “Fragnent -Lesecond sten-/Li corragiant: ) See Fragmans and stings Property validation Proptypes snort roptypes fron ‘prop: types" See Typechecking wth FropTypes any amthing serane fone Function boot Thue or fake eneoFien) num pee onsof ype sna) sion array arrayort) ones object objector.) Objactith values ofa cea ype instanceof) Instance ofa cass shape node OM node agus (+) iequared Pacuied ‘Also see 1 React weit ci 1 Peact0.14 chose Hooks API Reference Also see Hooks FA. usecontertmyconan Ful cota Baie Hooks ueorriondstatus( prope friend. dd); ‘value retuned from React .createcontext useteducerieceer ag) seal back => useRer tine usermporativenandee 0 (mi useLayoutef feet vsepebupraluaisie) ‘denial to usa fect but fas synchronous feral DOM manatone » donee, [ealtbsct)) eset unnountcongonentAtNoddannede) Rosctoonserver.randervastsng|-Soeporent />) ResctOowerver randerTeStatsctiarkup(-Camanent />) There ave more but hese ace moet common. See React top-evel APL Inner HTML, Function markdounsfy() (return *ep>.. Lists See Dangerousty set innetHTo, class TodeList tence component render () ( enat ( stems return
    [stems mp (sten )) = emis. props ‘Avays supply key propeny Returning strings render) { return ‘Look ma, 9 epan8!' : You can eur usta sing. See Fragments and stings Portals render 0) 6 return React creataPortal( ‘nia. props enaiaren, document getElenanty26(‘asnu) > , “This venders this. props.children into any location in the DOM. See Portals Basic types ycotponent proptypes ual: Proptypes. string seats: PropTypes.numbor. callback: Proptypes tune {stlosed: PropTypes. boa) any rosTypes. any Enumerables (oneOh) yo. proprypes = ( irection: Proptypes.o7o0t( "ieee", “right » } Custom validation ‘yc. proprypes = ( ‘ustowProp: (prove, key. conponenttane) —» ( Af (/natchno/,tast(preps[key])) ( return non Errar( "Validation Fasied!*) Errors class myconponest extends Component { componentOsstatah (error, nfo ‘this. satstate({ errer }) 3 Catch enor via couponentOidcatch. (Rese 16+) See fron handingin Rene 16 Hydration const ol = docunent.gotetonent8y14( app") Renct0OHnydrate(, el) Use ReactDU". hydrate instead of using ReactOOM.ronder youre rendering over the output of ResetDOMServe. See Hyate Required types yco.proptypes = ( rane: Proprypes.strang istequired Elements co. provtype node: Proprypes.node Arrays and objects "co. proprypes = ( ages: PropTypes.or/2)0"(PropTypes. unter) ser Broprypes object ser: Bropiyper.abjoct0*(ropTypas-runber) nessege: Proptypes arstance0f(hassoge) , "co. proprypes = ( ser: Prostypes. shape ( rane: Proprypes. string Proprypes number Use array(OFl. obsect[0F], snstenceot shape

You might also like