React (also known as React.js or ReactJS) is a JavaScript library for building user interfaces. It is maintained by Facebook and a community of individual developers and companies.
React can be used as a base in the development of single-page or mobile applications, as it is optimal for fetching rapidly changing data that needs to be recorded. However, fetching data is only the beginning of what happens on a web page, which is why complex React applications usually require the use of additional libraries for state management, routing, and interaction with an API.
1 of 296
More Related Content
30 days-of-react-ebook-fullstackio
2. Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/day-1/post.md)
What is React?
Today, we're starting out at the beginning. Let's look at what
React is and what makes it tick. We'll discuss why we want to
use it.
O e the ne t 3 da s, ou'll get a good feel fo the a ious pa ts of the React
https://facebook.github.io/ eact/ eb f ame o k and its ecos stem.
Each da in ou 3 da ad entu e ill build upon the p e ious da 's
mate ials, so b the end of the se ies, ou'll not onl kno the te ms,
concepts, and unde pinnings of ho the f ame o k o ks, but be able to use
React in ou ne t eb application.
Let's get sta ted. We'll sta t at the e beginning
https:// . outube.com/ atch? = RW3nDRmu6k as it's a e good
place to sta t.
React https://facebook.github.io/ eact/ is a Ja aSc ipt lib a fo building
use inte faces. It is the ie la e fo eb applications.
What is React?
1
3. At the hea t of all React applications a e components. A component is a self-
contained module that ende s some output. We can ite inte face
elements like a button o an input field as a React component. Components
a e composable. A component might include one o mo e othe components
in its output.
B oadl speaking, to ite React apps e ite React components that
co espond to a ious inte face elements. We then o ganize these
components inside highe -le el components hich define the st uctu e of
ou application.
Fo e ample, take a fo m. A fo m might consist of man inte face elements,
like input fields, labels, o buttons. Each element inside the fo m can be
itten as a React component. We'd then ite a highe -le el component,
the fo m component itself. The fo m component ould specif the st uctu e
of the fo m and include each of these inte face elements inside of it.
Impo tantl , each component in a React app abides b st ict data
management p inciples. Comple , inte acti e use inte faces often in ol e
comple data and application state. The su face a ea of React is limited and
aimed at gi ing us the tools to be able to anticipate ho ou application ill
look ith a gi en set of ci cumstances. We dig into these p inciples late in
the cou se.
React is a Ja aSc ipt f ame o k. Using the f ame o k is as simple as
including a Ja aSc ipt file in ou HTML and using the React e po ts in ou
application's Ja aSc ipt.
Fo instance, the Hello world e ample of a React ebsite can be as simple as:
Okay, so how do we use it?
2
4. <html>
<head>
<meta charset="utf-8">
<title>Hello world</title>
<!-- Script tags including React -->
<script
src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.min.js
"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-
dom.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js">
</script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
ReactDOM.render(
<h1>Hello world</h1>,
document.querySelector('#app')
);
</script>
</body>
</html>
Although it might look a little sca , the Ja aSc ipt code is a single line that
d namicall adds Hello world to the page. Note that e onl needed to
include a handful of Ja aSc ipt files to get e e thing o king.
Unlike man of its p edecesso s, React ope ates not di ectl on the b o se 's
Document Object Model DOM immediatel , but on a virtual DOM. That is,
athe than manipulating the document in a b o se afte changes to ou
data hich can be uite slo it esol es changes on a DOM built and un
enti el in memo . Afte the i tual DOM has been updated, React
intelligentl dete mines hat changes to make to the actual b o se 's DOM.
How does it work?
3
5. The React Vi tual DOM https://facebook.github.io/ eact/docs/dom-
diffe ences.html e ists enti el in-memo and is a ep esentation of the
eb b o se 's DOM. Because of this, e hen e ite a React component,
e' e not iting di ectl to the DOM, but e' e iting a i tual component
that React ill tu n into the DOM.
In the ne t a ticle, e'll look at hat this means fo us as e build ou React
components and jump into JSX and iting ou fi st eal components.
4
6. Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/day-2/post.md)
What is JSX?
Now that we know what React is, let's take a look at a few terms
and concepts that will come up throughout the rest of the
series.
In ou p e ious a ticle, e looked at hat React
https://facebook.github.io/ eact/ is and discussed at a high-le el ho it
o ks. In this a ticle, e' e going to look at one pa t of the React ecos stem:
ES and JSX.
In an cu so sea ch on the Inte net looking fo React mate ial, no doubt
ou ha e al ead un into the te ms JSX , ES , and ES . These opa ue
ac on ms can get confusing uickl .
ES the ES stands fo ECMASc ipt is basicall " egula Ja aSc ipt." The th
update to Ja aSc ipt, ES as finalized in 9. It has been suppo ted b all
majo b o se s fo se e al ea s. The efo e, if ou' e itten o seen an
Ja aSc ipt in the ecent past, chances a e it as ES .
ES is a ne e sion of Ja aSc ipt that adds some nice s ntactical and
functional additions. It as finalized in . ES is almost full suppo ted
http://kanga .github.io/compat-table/es / b all majo b o se s. But it
JSX/ES /ES WTF??!
5
7. ill be some time until olde e sions of eb b o se s a e phased out of use.
Fo instance, Inte net E plo e does not suppo t ES , but has about % of
the b o se ma ket sha e.
In o de to eap the benefits of ES toda , e ha e to do a fe things to get it
to o k in as man b o se s as e can:
. We ha e to transpile ou code so that a ide ange of b o se s
unde stand ou Ja aSc ipt. This means con e ting ES Ja aSc ipt into
ES Ja aSc ipt.
. We ha e to include a shim o polyfill that p o ides additional
functionalit added in ES that a b o se ma o ma not ha e.
We'll see ho e do this a bit late in the se ies.
Most of the code e'll rite in this series ill be easil
translatable to ES . In cases here e use ES , e'll
introduce the feature at first and then alk through it.
As e'll see, all of ou React components ha e a render function that
specifies hat the HTML output of ou React component ill be. JavaScript
eXtension, o mo e commonl JSX, is a React e tension that allo s us to
ite Ja aSc ipt that looks like HTML.
Although in pre ious paradigms it as ie ed as a bad habit
to include Ja aScript and markup in the same place, it turns
out that combining the ie ith the functionalit makes
reasoning about the ie straight-for ard.
6
8. To see hat this means, imagine e had a React component that ende s an
h1 HTML tag. JSX allo s us to decla e this element in a manne that closel
esembles HTML:
class HelloWorld extends React.Component {
render() {
return (
<h1 className='large'>Hello World</h1>
);
}
}
The render() function in the HelloWorld component looks like it's etu ning
HTML, but this is actuall JSX. The JSX is translated to egula Ja aSc ipt at
untime. That component, afte t anslation, looks like this:
class HelloWorld extends React.Component {
render() {
return (
React.createElement(
'h1',
{className: 'large'},
'Hello World'
)
);
}
}
While JSX looks like HTML, it is actuall just a te se a to ite a
React.createElement() decla ation. When a component ende s, it outputs a
t ee of React elements o a virtual representation of the HTML elements
this component outputs. React ill then dete mine hat changes to make to
the actual DOM based on this React element ep esentation. In the case of
the HelloWorld component, the HTML that React ites to the DOM ill
look like this:
<h1 class='large'>Hello World</h1>
7
9. The class extends s nta e used in our first React
component is ES s nta . It allo s us to rite objects using a
familiar Object-Oriented st le. In ES , the class s nta
might be translated as:
var HelloWorld = function() {}
Object.extends(HelloWorld, React.Component)
HelloWorld.prototype.render = function() {}
Because JSX is Ja aSc ipt, e can't use Ja aSc ipt ese ed o ds. This
includes o ds like class and for .
React gi es us the att ibute className . We use it in HelloWorld to set the
large class on ou h1 tag. The e a e a fe othe att ibutes, such as the for
att ibute on a label that React t anslates into htmlFor as for is also a
ese ed o d. We'll look at these hen e sta t using them.
If e ant to ite pu e Ja aSc ipt instead of el on a JSX compile , e can
just ite the React.createElement() function and not o about the la e
of abst action. But e like JSX. It's especiall mo e eadable ith comple
components. Conside the follo ing JSX:
<div>
<img src="profile.jpg" alt="Profile photo" />
<h1>Welcome back Ari</h1>
</div>
The Ja aSc ipt deli e ed to the b o se ill look like this:
8
10. React.createElement("div", null,
React.createElement("img", {src: "profile.jpg", alt: "Profile
photo"}),
React.createElement("h1", null, "Welcome back Ari")
);
Again, hile ou can skip JSX and ite the latte di ectl , the JSX s nta is
ell-suited fo ep esenting nested HTML elements.
No that e unde stand JSX, e can sta t iting ou fi st React
components. Join us tomo o hen e jump into ou fi st React app.
9
11. Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/day-3/post.md)
Our First Components
The first t o articles in this series ere hea y on discussion. In
today's session, let's di e into some code and rite our first
React app.
Let's re isit the "Hello orld" app e introduced on da one. Here it is again,
ritten slightl differentl :
10
12. <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello world</title>
<!-- Script tags including React -->
<script
src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.min.js
"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-
dom.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js">
</script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
var app = <h1>Hello world</h1>
var mountComponent = document.querySelector('#app');
ReactDOM.render(app, mountComponent);
</script>
</body>
</html>
We' e included the source of React as a <script> tag inside the <head>
element of our page. It's important to place our <script> loading tags before
e start riting our React application other ise the React and ReactDOM
ariables on't be defined in time for us to use them.
Also inside head is a script tag that includes a librar , babel-core . But hat
is babel-core ?
Hello world
Loading the React library
Babel
11
13. Yesterda , e talked about ES and ES . We mentioned that support for ES
is still spott . In order to use ES , it's best if e transpile our ES Ja aScript
into ES Ja aScript to support more bro sers.
Babel is a librar for transpiling ES to ES .
Inside body , e ha e a script bod . Inside of script , e define our first
React application. Note that the script tag has a type of text/babel :
<script type="text/babel">
This signals to Babel that e ould like it to handle the e ecution of the
Ja aScript inside this script bod , this a e can rite our React app using
ES Ja aScript and be assured that Babel ill li e-transpile its e ecution in
bro sers that onl support ES .
When using the babel-standalone package, e'll get a arning in the
console. This is fine and e pected. We'll s itch to a precompilation step in
a fe da s.
We' e included the <script /> tag here for ease of use.
Inside the Babel script bod , e' e defined our first React application. Our
application consists of a single element, the <h1>Hello world</h1> . The call
to ReactDOM.render() actuall places our tin React application on the page.
Without the call to ReactDOM.render() , nothing ould render in the DOM.
The first argument to ReactDOM.render() is what to render and the second is
where:
Warning in the console?
The React app
12
14. ReactDOM.render(<what>, <where>)
We' e ritten a React application. Our "app" is a React element hich
represents an h1 tag. But this isn't er interesting. Rich eb applications
accept user input, change their shape based on user interaction, and
communicate ith eb ser ers. Let's begin touching on this po er b
building our first React component.
We mentioned at the beginning of this series that at the heart of all React
applications are components. The best a to understand React components
is to rite them. We'll rite our React components as ES classes.
Let's look at a component e'll call App . Like all other React components,
this ES class ill e tend the React.Component class from the React package:
class App extends React.Component {
render() {
return <h1>Hello from our app</h1>
}
}
All React components e ui e at least a render() function.
This render() function is e pected to etu n a i tual DOM
ep esentation of the b o se DOM element s .
In our index.html , let's replace our Ja aScript from before ith our ne App
component.
Components and more
13
15. <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello world</title>
<!-- Script tags including React -->
<script
src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.min.js
"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-
dom.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js">
</script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
class App extends React.Component {
render() {
return <h1>Hello from our app</h1>
}
}
</script>
</body>
</html>
Ho e er, nothing is going to render on the screen. Do ou remember h ?
We ha en't told React e ant to render an thing on the screen or where to
render it. We need to use the ReactDOM.render() function again to e press to
React hat e ant rendered and here.
Adding the ReactDOM.render() function ill render our application on
screen:
var mount = document.querySelector('#app');
ReactDOM.render(<App />, mount);
Hello from our app
14
16. Notice that e can render our React app using the App class as though it is a
built-in DOM component t pe like the <h1 /> and <div /> tags . Here e're
using it as though it's an element ith the angle brackets: <App /> .
The idea that our React components act just like an other element on our
page allo s us to build a component tree just as if e ere creating a nati e
bro ser tree.
While e're rendering a React component no , our app still lacks richness or
interacti it . Soon, e'll see ho to make React components data-dri en and
d namic.
But first, in the ne t installment of this series, e'll e plore ho e can la er
components. Nested components are the foundation of a rich React eb
application.
Hello from our app
15
17. Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/day-4/post.md)
Complex Components
A esome, e' e built our first component. No let's get a bit
fancier and start building a more comple interface.
In the p e ious section of 30 Days of React, e sta ted building ou fi st React
component. In this section, e'll continue ou o k ith ou App component
and sta t building a mo e comple UI.
A common eb element e might see is a use timeline. Fo instance, e
might ha e an application that sho s a histo of e ents happening such as
applications like Facebook and T itte .
16
18. As e're not focusing on CSS
https:// . .org/standards/ ebdesign/htmlcss in this course,
e're not co ering the CSS specific to build the timeline as ou see it on
the screen.
Ho e er, e ant to make sure the timeline ou build looks similar to
ours. If ou include the follo ing CSS as a <link /> tag in our code,
ou're timeline ill look similar and ill be using the same st ling ours is
using:
<link
href="https://gist.githubusercontent.com/auser/2bc34b9abf07f34
f602dccd6ca855df1/raw/070d6cd5b4d4ec1a3e6892d43e877039a91a9108
/timeline.css" rel="stylesheet" type="text/css" />
The entire compiled CSS can be found on the gist at
https://gist.github.com/auser/ bc b abf f f dccd ca df
https://gist.github.com/auser/ bc b abf f f dccd ca df .
In addition, in order to make the timeline look e actl like the a ours
does on the site, ou'll need to include font-a esome
http://fonta esome.io/ in our eb application. There are multiple
a s to handle this. The simplest a is to include the link st les:
<link href="https://maxcdn.bootstrapcdn.com/font-
awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"
type="text/css" />
All the code for the e amples on the page is a ailable at the github repo
at https://github.com/fullstackreact/ -da s-of-react
https://github.com/fullstackreact/ -da s-of-react .
Styles
17
19. We could build this enti e UI in a single component. Ho e e , building an
enti e application in a single component is not a g eat idea as it can g o
huge, comple , and difficult to test.
18
21. alt='doug'
src="http://www.croop.cl/UI/twitter/images/doug.jpg" />
</div>
<span className="time">10 am</span>
<p>Read Day two article</p>
</div>
<div className="item">
<div className="avatar">
<img
alt='doug'
src="http://www.croop.cl/UI/twitter/images/doug.jpg" />
</div>
<span className="time">10 am</span>
<p>Lorem Ipsum is simply dummy text of the printing and
typesetting industry.</p>
</div>
<div className="item">
<div className="avatar">
<img
alt='doug'
src="http://www.croop.cl/UI/twitter/images/doug.jpg" />
</div>
<span className="time">2:21 pm</span>
<p>Lorem Ipsum has been the industry's standard dummy
text ever since the 1500s, when an unknown printer took a galley of
type and scrambled it to make a type specimen book.</p>
</div>
</div>
</div>
</div>
)
}
}
20
22. Rathe than build this in a single component, let's b eak it do n into multiple
components.
Looking at this component, the e a e sepa ate pa ts to the la ge
component as a hole:
. The title ba
. The content
Breaking it down
An hour ago
Ate lunch
10 am
Read Day two article
10 am
Lorem Ipsum is simply dummy text of the printing and
typesetting industry.
2:21 pm
Lorem Ipsum has been the industry's standard dummy
text ever since the 1500s, when an unknown printer
took a galley of type and scrambled it to make a type
specimen book.
Timeline
21
23. We can chop up the content pa t of the component into indi idual places of
conce n. The e a e diffe ent item components inside the content pa t.
22
24. If e anted to go one step further, e could e en break
do n the title bar into 3 component parts, the menu button,
the title, and the search icon. We could di e e en further into
each one of those if e needed to.
Deciding ho deep to split our components is more of an art than a
science and is a skill ou'll de elop ith e perience.
In an case, it's usuall a good idea to sta t looking at applications using the
idea of components. B b eaking ou app do n into components it becomes
easie to test and easie to keep t ack of hat functionalit goes he e.
To build ou notifications app, let's sta t b building the containe to hold the
enti e app. Ou containe is simpl going to be a appe fo the othe t o
components.
None of these components ill e ui e special functionalit et , so the ill
look simila to ou HelloWorld component in that it's just a component ith
a single ende function.
Let's build a appe component e'll call App that might look simila to this:
The container component
23
25. class App extends React.Component {
render() {
return (
<div className="notificationsFrame">
<div className="panel">
{/* content goes here */}
</div>
</div>
)
}
}
Notice that e use the attribute called className in React
instead of the HTML ersion of class . Remember that e're
not riting to the DOM directly and thus not riting HTML,
but JSX hich is just Ja aScript .
The reason e use className is because class is a reser ed ord in
Ja aScript. If e use class , e'll get an error in our console.
When a component is nested inside anothe component, it's called a child
component. A component can ha e multiple child en components. The
component that uses a child component is then called it's parent component.
With the appe component defined, e can build ou title and content
components b , essentiall , g abbing the sou ce f om ou o iginal design and
putting the sou ce file into each component.
Fo instance, the heade component looks like this, ith a containe element
<div className="header"> , the menu icon, a title, and the sea ch ba :
Child components
24
26. class Header extends React.Component {
render() {
return (
<div className="header">
<div className="fa fa-more"></div>
<span className="title">Timeline</span>
<input
type="text"
className="searchInput"
placeholder="Search ..." />
<div className="fa fa-search searchIcon"></div>
</div>
)
}
}
And finall , e can ite the Content component ith timeline items. Each
timeline item is apped in a single component, has an a ata associated
ith it, a timestamp, and some te t.
Timeline
25
28. In order to rite a comment in a React component, e ha e
to place it in the brackets as a multi-line comment in
Ja aScript.
Unlike the HTML comment that looks like this:
<!-- this is a comment in HTML -->
the React ersion of the comment must be in brackets:
{/* This is a comment in React */}
No that e ha e ou t o children components, e can set the Header and
the Content components to be children of the App component. Ou App
component can then use these components as if they are HTML elements
built-in to the bro ser. Ou ne App component, ith a heade and content
no looks like:
class App extends React.Component {
render() {
return (
<div className="notificationsFrame">
<div className="panel">
<Header />
<Content />
</div>
</div>
)
}
}
Putting it all together
27
29. With this kno ledge, e no ha e the abilit to ite multiple components
and e can sta t to build mo e comple applications.
Ho e e , ou ma notice that this app does not ha e an use inte action no
custom data. In fact, as it stands ight no ou React application isn't that
much easie to build than st aight, no-f ills HTML.
In the ne t section, e'll look ho to make ou component mo e d namic
and become data-dri en ith React.
An hour ago
Ate lunch 2
Timeline
28
30. Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/day-5/post.md)
Data-Driven
Hard-coding data in our applications isn't e actl ideal. Toda ,
e'll set up our components to be dri en b data to them access
to e ternal data.
Through this point, e' e ritten our first components and set them up in a
child/parent relationship. Ho e er, e ha en't et tied an data to our React
components. Although it's a more pleasant e perience in our opinion
riting a ebsite in React, e ha en't taken ad antage of the po er of React
to displa an d namic data.
Let's change that toda .
Recall, esterda e built the beginning of our timeline component that
includes a header and an acti it list:
Going data-driven
An hour ago
Timeline
29
31. We broke do n our demo into components and ended up building three
separate components ith static JSX templates. It's not er con enient to
ha e to update our component's template e er time e ha e a change in our
ebsite's data.
Instead, let's gi e the components data to use to displa . Let's start ith the
<Header /> component. As it stands right no , the <Header /> component
onl sho s the title of the element as Timeline . It's a nice element and it
ould be nice to be able to reuse it in other parts of our page, but the title of
Timeline doesn't make sense for e er use.
Let's tell React that e ant to be able to set the title to something else.
React allo s us to send data to a component in the same s nta as HTML,
using attributes or properties on a component. This is akin to passing the
src attribute to an image tag. We can think about the propert of the <img
Introducing props
Ate lunch
10 am
Read Day two article
10 am
Lorem Ipsum is simply dummy text of the printing and
typesetting industry.
2:21 pm
Lorem Ipsum has been the industry's standard dummy
text ever since the 1500s, when an unknown printer
took a galley of type and scrambled it to make a type
specimen book.
30
32. /> tag as a prop e're setting on a component called img .
We can access these properties inside a component as this.props . Let's see
props in action.
Recall, e defined the <Header /> component as:
class Header extends React.Component {
render() {
return (
<div className="header">
<div className="fa fa-more"></div>
<span className="title">Timeline</span>
<input
type="text"
className="searchInput"
placeholder="Search ..." />
<div className="fa fa-search searchIcon"></div>
</div>
)
}
}
When e use the <Header /> component, e placed it in our <App />
component as like so:
<Header />
31
33. We can pass in our title as a prop as an attribute on the <Header /> b
updating the usage of the component setting the attribute called title to
some string, like so:
<Header title="Timeline" />
Inside of our component, e can access this title prop from the
this.props propert in the Header class. Instead of setting the title staticall
as Timeline in the template, e can replace it ith the propert passed in.
Timeline
32
34. class Header extends React.Component {
render() {
return (
<div className="header">
<div className="menuIcon">
<div className="dashTop"></div>
<div className="dashBottom"></div>
<div className="circle"></div>
</div>
<span className="title">
{this.props.title}
</span>
<input
type="text"
className="searchInput"
placeholder="Search ..." />
<div className="fa fa-search searchIcon"></div>
</div>
)
}
}
We' e also updated the code slightly to get close to hat ou
final <Header /> code ill look like, including adding a
searchIcon and a fe elements to style the menuIcon .
No our <Header /> component ill displa the string e pass in as the
title hen e call the component. For instance, calling our <Header />
component four times like so:
33
35. <Header title="Timeline" />
<Header title="Profile" />
<Header title="Settings" />
<Header title="Chat" />
Results in four <Header /> components to mount like so:
Prett nift , e ? No e can reuse the <Header /> component ith a
d namic title propert .
We can pass in more than just strings in a component. We can pass in
numbers, strings, all sorts of objects, and e en functions! We'll talk more
about ho to define these different properties so e can build a component
api later.
Instead of staticall setting the content and date Let's take the Content
component and set the timeline content b a data ariable instead of b te t.
Just like e can do ith HTML components, e can pass multiple props into
a component.
Recall, esterda e defined our Content container like this:
Timeline
Profile
Settings
Chat
34
36. class Content extends React.Component {
render() {
return (
<div className="content">
<div className="line"></div>
{/* Timeline item */}
<div className="item">
<div className="avatar">
<img src="http://www.croop.cl/UI/twitter/images/doug.jpg"
/>
Doug
</div>
<span className="time">
An hour ago
</span>
<p>Ate lunch</p>
<div className="commentCount">
2
</div>
</div>
{/* ... */}
</div>
)
}
}
As e did ith title , let's look at hat props our Content component
needs:
A user's a atar image
A timestamp of the acti it
Te t of the acti it item
Number of comments
35
37. Let's sa that e ha e a Ja aScript object that represents an acti it item. We
ill ha e a fe fields, such as a string field te t and a date object. We might
ha e some nested objects, like a user and comments . For instance:
{
timestamp: new Date().getTime(),
text: "Ate lunch",
user: {
id: 1,
name: 'Nate',
avatar: "http://www.croop.cl/UI/twitter/images/doug.jpg"
},
comments: [
{ from: 'Ari', text: 'Me too!' }
]
}
Just like e passed in a string title to the <Header /> component, e can
take this acti it object and pass it right into the Content component. Let's
con ert our component to displa the details from this acti it inside it's
template.
In order to pass a d namic ariable's alue into a template, e ha e to use the
template s nta to render it in our template. For instance:
36
39. We' e use a little bit of ES6 in ou class definition on the fi st
line of the render() function called destructuring. The t o
follo ing lines a e functionally e ui alent:
// these lines do the same thing
const activity = this.props.activity;
const {activity} = this.props;
Destructuring allo s us to sa e on typing and define ariables in a
shorter, more compact ay.
We can then use this ne content b passing in an object as a prop instead of
a hard-coded string. For instance:
<Content activity={moment1} />
Fantastic, no e ha e our acti it item dri en b an object. Ho e er, ou
might ha e noticed that e ould ha e to implement this multiple times ith
different comments. Instead, e could pass an arra of objects into a
component.
1509490290341
Ate lunch 1
38
40. Let's sa e ha e an object that contains multiple acti it items:
const activities = [
{
timestamp: new Date().getTime(),
text: "Ate lunch",
user: {
id: 1, name: 'Nate',
avatar: "http://www.croop.cl/UI/twitter/images/doug.jpg"
},
comments: [{ from: 'Ari', text: 'Me too!' }]
},
{
timestamp: new Date().getTime(),
text: "Woke up early for a beautiful run",
user: {
id: 2, name: 'Ari',
avatar: "http://www.croop.cl/UI/twitter/images/doug.jpg"
},
comments: [{ from: 'Nate', text: 'I am so jealous' }]
},
]
We can rearticulate our usage of <Content /> b passing in multiple
acti ities instead of just one:
<Content activities={activities} />
Ho e er, if e refresh the ie nothing ill sho up! We need to first update
our Content component to accept multiple acti ities. As e learned about
pre iousl , JSX is reall just Ja aScript e ecuted b the bro ser. We can
e ecute Ja aScript functions inside the JSX content as it ill just get run b
the bro ser like the rest of our Ja aScript.
Let's mo e our acti it item JSX inside of the function of the map function
that e'll run o er for e er item.
39
42. No e can pass an number of acti ities to our arra and the Content
component ill handle it, ho e er if e lea e the component right no , then
e'll ha e a relati el comple component handling both containing and
displa ing a list of acti ities. Lea ing it like this reall isn't the React a .
Here is here it makes sense to rite one more component to contain
displa ing a single acti it item and then rather than building a comple
Content component, e can mo e the responsibilit . This ill also make it
easier to test, add functionalit , etc.
Let's update our Content component to displa a list of ActivityItem
components e'll create this ne t .
ActivityItem
Woke up early for a beautiful run 1
41
43. class Content extends React.Component {
render() {
const {activities} = this.props; // ES6 destructuring
return (
<div className="content">
<div className="line"></div>
{/* Timeline item */}
{activities.map((activity) => (
<ActivityItem
activity={activity} />
))}
</div>
)
}
}
Not onl is this much simpler and easier to understand, but it makes testing
both components easier.
With our freshl -minted Content component, let's create the ActivityItem
component. Since e alread ha e the ie created for the ActivityItem , all
e need to do is cop it from hat as our Content component's template
as it's o n module.
42
44. class ActivityItem extends React.Component {
render() {
const {activity} = this.props; // ES6 destructuring
return (
<div className="item">
<div className="avatar">
<img
alt={activity.text}
src={activity.user.avatar} />
{activity.user.name}
</div>
<span className="time">
{activity.timestamp}
</span>
<p>{activity.text}</p>
<div className="commentCount">
{activity.comments.length}
</div>
</div>
)
}
}
1509490290341
Ate lunch 1
1509490290341
Woke up early for a beautiful run 1
43
45. This eek e updated our components to be dri en b data b using the
React props concept. In the ne t section, e'll di e into stateful components.
44
46. Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/day-6/post.md)
State
Toda e're getting started on ho stateful components ork in
React and look at hen and h e'll use state.
We' e almost made it through the rst eek of getting up and running on
React. We ha e orked through JSX, building our rst components, setting
up parent-child relationships, and dri ing our component properties ith
React. We ha e one more major idea e ha e et to discuss about React, the
idea of state.
React does not allo us to modif this.props on our components for good
reason. Imagine if e passed in the title prop to the Header component
and the Header component as able to modif it. Ho do e kno hat the
title is of the Header component? We set oursel es up for race-conditions,
confusing data state, and it ould be an all-around bad idea to modif a
ariable passed to a child component b a parent component.
Ho e er, sometimes a component needs to be able to update it's o n state.
For e ample, setting an active ag if a child component needs to sho it's
selected or updating a timer on a stop atch, for e ample.
The state of things
45
47. While it's preferable to use props as much as e can, sometimes e need to
hold on to the state of a component. To handle this, React gi es us the abilit
to hold state in our components.
state in a component is intended to be completel internal to the
Component and it's children i.e. accessed b the component and an
children it used . Similar to ho e access props in a component, the state
can be accessed ia this.state in a component. Whene er the state changes
ia the this.setState() function , the component ill rerender.
For instance, let's sa e ha e a simple clock component that sho s the
current time:
E en though this is a simple clock component, it does retain state in that it
needs to kno hat the current time is to displa . Without using state , e
could set a timer and rerender the entire React component, but other
components on the page ma not need rerendering... this ould become a
headache and slo hen e integrate it into a more comple application.
Instead, e can set a timer to call rerender inside the component and change
just the internal state of this component.
Let's take a stab at building this component. First, e'll create the component
e'll call Clock .
3:51:36 pm
46
48. Before e get into the state, let's build the component and create the
render() function. We'll need to take into account the number and prepend
a zero 0 to the number if the numbers are smaller than and set the
am/pm appropriatel . The end result of the render() function might look
something like this:
class Clock extends React.Component {
render() {
const currentTime = new Date(),
hours = currentTime.getHours(),
minutes = currentTime.getMinutes(),
seconds = currentTime.getSeconds(),
ampm = hours >= 12 ? 'pm' : 'am';
return (
<div className="clock">
{
hours == 0 ? 12 :
(hours > 12) ?
hours - 12 : hours
}:{
minutes > 9 ? minutes : `0${minutes}`
}:{
seconds > 9 ? seconds : `0${seconds}`
} {ampm}
</div>
)
}
}
47
49. Alternati ely, e could use the short snippet to handle padding the clock
time:
("00" + minutes).slice(-2)
But e' e opted to be more clear ith the pre ious code.
If e render our ne Clock component, e ill onl get a time rendered
e er time the component itself rerenders. It's not a er useful clock et . In
order to con ert our static time displa Clock component into a clock that
displa s the time, e'll need to update the time e er second.
In order to do that, e'll need to track the current time in the state of the
component. To do this, e'll need to set an initial state alue.
In the ES6 class st le, e can set the initial state of the component in the
constructor() b setting this.state to a alue.
constructor(props) {
super(props);
this.state = this.getTime();
}
The first line of the constructor should always call
super(props) . If ou forget this, the component on't like
ou er much i.e. there ill be errors .
Alternative padding technique
48
50. No that e ha e a this.state de ned in our Clock component, e can
reference it in the render() function using the this.state . Let's update our
render() function to grab the alues from this.state :
class Clock extends React.Component {
// ...
render() {
const {hours, minutes, seconds, ampm} = this.state;
return (
<div className="clock">
{
hours === 0 ? 12 :
(hours > 12) ?
hours - 12 : hours
}:{
minutes > 9 ? minutes : `0${minutes}`
}:{
seconds > 9 ? seconds : `0${seconds}`
} {ampm}
</div>
)
}
}
Instead of orking directl ith data alues, e can no update the state of
the component and separate the render() function from the data
management.
In order to update the state, e'll use a special function called: setState() ,
hich ill trigger the component to rerender.
We need to call setState() on the this alue of the
component as it's a part of the React.Component class e are
subclassing.
49
51. In our Clock component, let's use the nati e setTimeout() Ja aScript
function to create a timer to update the this.state object in
milliseconds. We'll place this functionalit in a function as e'll ant to call
this again.
class Clock extends React.Component {
// ...
constructor(props) {
super(props);
this.state = this.getTime();
}
// ...
setTimer() {
clearTimeout(this.timeout);
this.timeout = setTimeout(this.updateClock.bind(this), 1000);
}
// ...
updateClock() {
this.setState(this.getTime, this.setTimer);
}
// ...
}
We ill get into the lifec cle hooks in the ne t section, but
for the time being e'll call this in the constructor() for
simplicit .
In the updateClock() function e'll ant to update the state ith the ne
time. We can no update the state in the updateClock() function:
50
52. class Clock extends React.Component {
// ...
updateClock() {
this.setState(this.getTime, this.setTimer);
}
// ...
}
The component ill be mounted on the page and in appro imatel one
second milliseconds it updates the current time. Ho e er, it on't be
reset again. We can simpl call the setTimer() function again at the end of
the function:
class Clock extends React.Component {
// ...
updateClock() {
const currentTime = new Date();
this.setState({
currentTime: currentTime
})
this.setTimer();
}
// ...
}
No the component itself might rerender slo er than the timeout function
gets called again, hich ould cause a rerendering bottleneck and needlessl
using up precious batter on mobile de ices. Instead of calling the
setTimer() function after e call this.setState() , e can pass a second
argument to the this.setState() function hich ill be guaranteed to be
called after the state has been updated.
51
53. class Clock extends React.Component {
// ...
updateClock() {
const currentTime = new Date();
this.setState({
currentTime: currentTime
}, this.setTimer);
}
// ...
}
When e call this.setState() ith an object argument, it
ill perform a shallow merge of the data into the object
a ailable ia this.state and then ill rerender the
component.
We generall onl ant to keep alues in our state that e'll
use in the render() function. From the e ample abo e ith
our clock, notice that e stored the hours , minutes , and
seconds in our state. It's usuall a bad idea to store objects
or calculations in the state that e don't plan on using in the
render function as it can cause unnecessar rendering and
asteful CPU c cles.
3:51:36 pm
Some things to keep in mind
52
54. As e noted at the top of this section, it's preferred to use props hen
a ailable not onl for performance reasons, but because stateful components
are more dif cult to test.
Toda , e' e updated our components to be stateful and no ha e a handle
on ho to make a component stateful hen necessar . Tomorro e'll di e
into the lifec cle of a component and hen/ho to interact ith the page.
53
55. Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/day-7/post.md)
Lifecycle Hooks
Today, we'll look through a few of the most common lifecycle
hooks we can use with React components and we'll discuss why
they are useful and when we should each one.
Cong ats! We' e made it to the end of the fi st eek on React and e' e
al ead co e ed so much g ound. We just finished o king ith stateful
components to keep t ack of a component's inte nal state. Toda , e' e going
to pause on implementation and talk a bit about ho a component lives in an
application. That is, e'll talk about the component's lifec cle.
As React mounts ou application, it gi es us some hooks he e e can inse t
ou o n functionalit at diffe ent times in the component's lifec cle. In o de
to hook into the lifec cle, e'll need to define functions on ou component
hich React calls at the app op iate time fo each hook. Let's di e into the
fi st lifec cle hook:
When a component is defined on a page in ou application, e can't depend
upon it being a ailable in the DOM immediatel as e' e defining i tual
nodes. Instead, e ha e to ait until the component itself has actuall
mounted in the b o se . Fo functionalit that e need to un hen it has
componentWillMount() /
componentDidMount()
54
56. been mounted, e get t o diffe ent hooks o functions e can define. One
that is called just befo e the component is due to be mounted on the page
and one that is called just afte the component has been mounted.
Since e're defining virtual representations of nodes in our DOM tree
ith React, e're not actually defining DOM nodes. Instead, e're
building up an in-memory ie that React maintains and manages for us.
When e talk about mounting, e're talking about the process of
con erting the irtual components into actual DOM elements that are
placed in the DOM by React.
This is useful fo things such as fetching data to populate the component. Fo
instance, let's sa that e ant to use ou acti it t acke to displa github
e ents, fo e ample. We ill ant to load these e ents onl hen the data
itself is going to be ende ed.
Recall e defined ou Content component in ou acti it list:
What does mounting mean?
55
57. class Content extends React.Component {
render() {
const {activities} = this.props; // ES6 destructuring
return (
<div className="content">
<div className="line"></div>
{/* Timeline item */}
{activities.map((activity) => (
<ActivityItem
activity={activity} />
))}
</div>
)
}
}
Let's update the Content component to make a e uest to the github.com
e ents api https://de elope .github.com/ 3/acti it /e ents/ and use the
esponse to displa the acti ities. As such, e'll need to update the state of
the object.
As e did este da , let's update ou component to be stateful b setting
this.state to an object in the const ucto
56
58. class Content extends React.Component {
constructor(props) {
super(props);
this.state = {
activities: []
}
}
// ...
}
No , e'll ant to make an HTTP e uest hen the component itself is
getting ead to be mounted o just afte it mounts . B defining the function
componentWillMount() o componentDidMount() in ou component, React
uns the method just befo e it mounts in the DOM. This is a pe fect spot fo
us to add a GET e uest.
Let's update the Content component ith the e uest to the github api.
Since e'll onl ant to displa a small list, let's take the latest fou e ents.
We' e sto ed a static JSON file of github data that e'll load
di ectly f om sou ce he e e'll get back to making AJAX
e uests in a fe days using p omises. Fo no , let's focus on
ho e'll implement updating ou component ith ne data:
class Content extends React.Component {
// ...
componentWillMount() {
this.setState({activities: data});
}
// ...
}
57
59. Notice that e didn't change an thing else f om ou Content component and
it just o ks.
Sometimes e'll ant to update some data of ou component befo e o afte
e change the actual ende ing. Fo instance, let's sa e ant to call a
function to set up the ende ing o call a function set hen a component's
p ops a e changed. The componentWillUpdate() method is a easonable hook
to handle p epa ing ou component fo a change as long as e don't call
this.setState() to handle it as it ill cause an infinite loop .
Since e on't eall need to handle this in-depth, e on't o about
setting up an e ample he e, but it's good to kno it e ists. A mo e common
lifec cle hook e'll use is the componentWillReceiveProps() hook.
React ill call a method hen the component is about to ecei e ne props .
This is the fi st method that ill be called hen a component is going to
ecei e a ne set of p ops. Defining this method is a good time to look fo
updates to specific props as it gi es us an oppo tunit to calculate changes
and update ou component's inte nal state.
This is the time hen e can update ou state based on ne p ops.
componentWillUpdate() /
componentDidUpdate()
componentWillReceiveProps()
58
60. One thing to keep in mind he e is that e en though the
componentWillReceiveProps() method gets called, the alue of
the props may not ha e changed. It's always a good idea to
check fo changes in the p op alues.
Fo instance, let's add a refresh button to ou acti it list so ou use s can
e uest a e e uest of the github e ents api.
We'll use the componentWillReceiveProps() hook to ask the component to
eload it's data. As ou component is stateful, e'll ant to ef esh this state
ith ne data, so e can't simpl update the props in a component. We can
use the componentWillReceiveProps() method to tell the component e ant
a ef esh.
Let's add a button on ou containing element that passes a requestRefresh
boolean p op to tell the Content component to ef esh.
59
61. class Container extends React.Component {
constructor(props) {
super(props);
this.state = {refreshing: false}
}
// Bound to the refresh button
refresh() {
this.setState({refreshing: true})
}
// Callback from the `Content` component
onComponentRefresh() {
this.setState({refreshing: false});
}
render() {
const {refreshing} = this.state;
return (
<div className='notificationsFrame'>
<div className='panel'>
<Header title="Github activity" />
{/* refreshing is the component's state */}
<Content
onComponentRefresh={this.onComponentRefresh.bind(this)}
requestRefresh={refreshing}
fetchData={fetchEvents} />
{/* A container for styling */}
<Footer>
<button onClick={this.refresh.bind(this)}>
<i className="fa fa-refresh" />
Refresh
</button>
</Footer>
</div>
</div>
)
}
}
60
62. Notice that e ha e a ne element here that displays the children of the
element. This is a pattern hich allo s us to add a CSS class around some
content.
class Footer extends React.Component {
render() {
return (
<div className='footer'>
{this.props.children}
</div>
)
}
}
Using this ne prop the requestRefresh p op , e can update the
activities f om ou state object hen it changes alue.
class Content extends React.Component {
// ...
componentWillReceiveProps(nextProps) {
// Check to see if the requestRefresh prop has changed
if (nextProps.requestRefresh !== this.props.requestRefresh) {
this.setState({loading: true}, this.updateData);
}
}
// ...
}
<Footer />
61
63. This demo is using static data f om a JSON file and andomly
picking fou elements hen e ef esh. This is set up to
simulate a ef esh.
Befo e the component is unmounted, React ill call out to the
componentWillUnmount() callback. This is the time to handle an clean-up
e ents e might need, such as clea ing timeouts, clea ing data,
disconnecting ebsockets, etc.
Fo instance, ith ou clock component e o ked on last time, e set a
timeout to be called e e second. When the component is ead to
unmount, e ant to make su e e clea this timeout so ou Ja aSc ipt
doesn't continue unning a timeout fo components that don't actuall e ist.
Recall that ou timer component e built looks like this:
componentWillUnmount()
62
64. class Clock extends React.Component {
constructor(props) {
super(props);
this.state = this.getTime();
}
componentDidMount() {
this.setTimer();
}
setTimer() {
this.timeout = setTimeout(this.updateClock.bind(this), 1000);
}
updateClock() {
this.setState(this.getTime, this.setTimer);
}
getTime() {
const currentTime = new Date();
return {
hours: currentTime.getHours(),
minutes: currentTime.getMinutes(),
seconds: currentTime.getSeconds(),
ampm: currentTime.getHours() >= 12 ? 'pm' : 'am'
}
}
// ...
render() {
}
}
When ou clock is going to be unmounted, e'll ant to clea the timeout e
c eate in the setTimer() function on the component. Adding the
componentWillUnmount() function takes ca e of this necessa cleanup.
63
65. class Clock extends React.Component {
// ...
componentWillUnmount() {
if (this.timeout) {
clearTimeout(this.timeout);
}
}
// ...
}
These a e a fe of the lifec cle hooks e can inte act ith in the React
f ame o k. We'll be using these a lot as e build ou eact apps, so it's a good
idea to be familia ith them, that the e ist, and ho to hook into the life of
a component.
We did int oduce one ne concept in this post hich e glossed o e : e
added a callback on a component to be called f om the child to it's pa ent
component. In the ne t section, e' e going to look at ho to define and
document the prop API of a component fo usage hen sha ing a
component ac oss teams and an application in gene al.
64
66. Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/day-8/post.md)
Packaging and PropTypes
We're looking at how to make reusable React components today
so that not only can we share our components across apps and
teams.
Phe ! We made it to eek t o elati el unscathed ! Th ough this point,
e' e talked th ough most of the basic featu es of React props , state , life-
c cle hooks, JSX, etc. .
In this section, e' e going to look a bit at annotating and packaging ou
components.
You ma ha e noticed e use props uite a bit in ou components. Fo the
most pa t, e'll e pect these to be a pa ticula t pe o set of t pes aka an
object o a string . React p o ides a method fo defining and alidating
these t pes that allo us to easil e pose a component API.
Not onl is this a good p actice fo documentation pu poses, it's g eat fo
building eusable eact components
https://facebook.github.io/ eact/docs/ eusable-components.html .
PropTypes
65
67. The prop-types object e po ts a bunch of diffe ent t pes hich e can use
to define hat t pe a component's p op should be. We can define these using
the propTypes method in the ES6 class-st le React p op:
class Clock extends React.Component {
// ...
}
Clock.propTypes = {
// key is the name of the prop and
// value is the PropType
}
F om ithin this prop , e can define an object hich has the ke of a p op
as the name of the p op e a e defining and a alue defines the t pe o
t pes it should be defined as.
Fo instance, the Header component e built a fe da s ago accepts a a p op
called title and e e pect it to be a st ing. We can define it's t pe to be a
st ing as such:
First, we'll need to import the PropTypes package from the
prop-types package using the import keyword again:
import PropTypes from 'prop-types'
66
68. import PropTypes from 'prop-types'
class Header extends React.Component {
// ...
}
Header.propTypes = {
title: PropTypes.string
}
React has a lot of t pes to choose f om, e po ted on the PropTypes object
and e en allo s fo us to define a custom object t pe. Let's look at an o e all
list of a ailable t pes:
React e poses a fe basic t pes e can use out of the bo .
type example class
type example class
String 'hello' PropTypes.string
Number 10, 0.1 PropTypes.number
Boolean true / false PropTypes.bool
Function
const say => (msg) => console.log("Hello
world")
PropTypes.func
Symbol Symbol("msg") PropTypes.symbol
Object {name: 'Ari'} PropTypes.object
Anything 'whatever', 10, {}
It's possible to tell React e ant it to pass th ough anything that can be
ende ed b using PropTypes.node :
type exampleclass
type exampleclass
A rendererable10, 'hello' PropTypes.node
Basic types
67
69. Clock.propTypes = {
title: PropTypes.string,
count: PropTypes.number,
isOn: PropTypes.bool,
onDisplay: PropTypes.func,
symbol: PropTypes.symbol,
user: PropTypes.object,
name: PropTypes.node
}
We' e al ead looked at ho to communicate f om a pa ent component to a
child component using props . We can communicate f om a child component
to a pa ent component using a function. We'll use this patte n uite often
hen e ant to manipulate a pa ent component f om a child.
We can pass th ough ite able collections in ou props . We' e al ead seen
ho e can do this hen e passed th ough an a a ith ou acti ities. To
decla e a component's p opt pe as an a a , e can use the PropTypes.array
annotation.
We can also e ui e that an a a holds onl objects of a ce tain t pe using
PropTypes.arrayOf([]) .
type example class
type example class
Array [] PropTypes.array
Array of numbers [1, 2, 3] PropTypes.arrayOf([type])
Enum ['Red', 'Blue'] PropTypes.oneOf([arr])
It's possible to desc ibe an object that can be one of a fe diffe ent t pes as
ell using PropTypes.oneOfType([types]) .
Collection types
68
70. Clock.propTypes = {
counts: PropTypes.array,
users: PropTypes.arrayOf(PropTypes.object),
alarmColor: PropTypes.oneOf(['red', 'blue']),
description: PropTypes.oneOfType([
PropTypes.string,
PropTypes.instanceOf(Title)
]),
}
It's possible to define t pes that need to be of a ce tain shape o instance of a
ce tain class.
type example class
type example class
Object {name: 'Ari'} PropTypes.object
Number object {count: 42} PropTypes.objectOf()
Instance new Message() PropTypes.objectOf()
Object shape {name: 'Ari'} PropTypes.shape()
Clock.propTypes = {
basicObject: PropTypes.object,
numbers: PropTypes
.objectOf(PropTypes.numbers),
messages: PropTypes
.instanceOf(Message),
contactList: PropTypes.shape({
name: PropTypes.string,
phone: PropTypes.string,
})
}
Object types
React types
69
71. We can also pass th ough React elements f om a pa ent to a child. This is
inc edibl useful fo building templates and p o iding customization ith the
templates.
type example class
type example class
Element <Title /> PropTypes.element
Clock.propTypes = {
displayEle: PropTypes.element
}
When e use element, React e pects that e'll be able to accept a single child
component. That is, e on't be able to pass multiple elements.
// Invalid for elements
<Clock displayElement={
<div>Name</div>
<div>Age</div>
}></Clock>
// Valid
<Clock displayElement={
<div>
<div>Name</div>
<div>Age</div>
</div>
}></Clock>
It's possible to e ui e a p op to be passed to a component b appending any
of the p opt pe desc iptions ith .isRequired :
Clock.propTypes = {
title: PropTypes.name.isRequired,
}
Requiring types
70
72. Setting a prop as e ui ed is e useful fo times hen the component is
dependent upon a prop to be passed in b it's pa ent component and on't
o k ithout it.
Finall , it's also possible to pass a function to define custom t pes. We can do
this fo a single p op o to alidate a a s. The one e ui ement fo the
custom function is that if the alidation does not pass, it e pects e'll etu n
an Error object:
type example class
type example class
Custom 'something_crazy'
function(props, propName, componentName)
{}
CustomArray
['something',
'crazy']
PropTypes.arrayOf(function(props, propName,
componentName) {})
UserLink.propTypes = {
userWithName: (props, propName, componentName) => {
if (!props[propName] || !props[propName].name) {
return new Error(
"Invalid " + propName + ": No name property defined for
component " + componentName
)
}
}
}
Sometimes e ant to be able to set a default alue fo a p op. Fo instance,
ou <Header /> component, e built este da might not e ui e a title to be
passed. If it's not, e'll still ant a title to be ende ed, so e can define a
common title instead b setting it's default p op alue.
To set a default p op alue, e can use the defaultProps object ke on the
component.
Custom types
Default props
71
73. Header.defaultProps = {
title: 'Github activity'
}
Phe , toda e ent th ough a lot of documentation. It's always a good idea
to build ou esuable components using the propTypes and defaultProps
att ibutes of components. Not onl ill it make it easie to communicate
ac oss de elope s, it'll be much easie hen e etu n to ou components
afte lea ing them fo a fe da s.
Ne t, e'll get back to code and sta t integ ating some st le into ou
components.
72
74. Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/day-9/post.md)
Styles
No application is complete without style. We'll look at the
different methods we can use to style our components, from
traditional CSS to inline styling.
Th ough this point, e ha en't touched the st ling of ou components
be ond attaching Cascading St leSheet CSS class names to components.
Toda , e'll spend time o king th ough a fe a s ho to st le ou React
components to make them look g eat, et still keeping ou sanit . We'll e en
o k th ough making o king ith CSS a bit easie too!
Let's look at a fe of the diffe ent a s e can st le a component.
. CasCasding St lesheets CSS
. Inline st les
. St ling lib a ies
Using CSS to st le ou eb applications is a p actice e' e al ead familia
ith and is nothing ne . If ou' e e e itten a eb application befo e, ou
most likel ha e used/ itten CSS. In sho t, CSS is a a fo us to add st le
to a DOM component outside of the actual ma kup itself.
CSS
73
75. Using CSS alongside React isn't no el. We'll use CSS in React just like e use
CSS hen not using React. We'll assign ids/classes to components and use
CSS selecto s to ta get those elements on the page and let the b o se
handle the st ling.
As an e ample, let's st le ou Header component e' e been o king ith a
bit.
Let's sa e anted to tu n the heade colo o ange using CSS. We can easil
handle this b adding a st lesheet to ou page and ta geting the CSS class of
.header in a CSS class.
Recall, the ende function of ou Header component cu entl looks like
this:
Orange header
74
76. class Header extends React.Component {
render() {
// Classes to add to the <input /> element
let searchInputClasses = ["searchInput"];
// Update the class array if the state is visible
if (this.state.searchVisible) {
searchInputClasses.push("active");
}
return (
<div className="header">
<div className="fa fa-more"></div>
<span className="title">
{this.props.title}
</span>
<input
type="text"
className={searchInputClasses.join(' ')}
placeholder="Search ..." />
<div className="fa fa-search searchIcon"></div>
</div>
)
}
}
We can ta get the header b de ning the st les fo a .header class in a
egula css le. As pe -usual, e'll need to make su e e use a <link /> tag
to include the CSS class in ou HTML page. Supposing e de ne ou st les in
a le called styles.css in the same di ecto as the index.html le, this
<link /> tag ill look like the follo ing:
<link rel="stylesheet" type="text/css" href="styles.css">
Let's ll in the st les fo the Header class names:
75
77. .header {
background: rgba(251, 202, 43, 1);
}
.header, .fa, .title, .searchIcon {
color: #333333;
}
One of the most common complaints about CSS in the st place is the
cascading featu e itself. The a CSS o ks is that it cascades hence the
name pa ent st les to it's child en. This is often a cause fo bugs as classes
often ha e common names and it's eas to o e ite class st les fo non-
speci c classes.
Using ou e ample, the class name of .header isn't e speci c. Not onl
could the page itself ha e a heade , but content bo es on the page might,
a ticles, e en ads e place on the page might ha e a class name of .header .
One a e can a oid this p oblem is to use something like
css modules https://glenmadde n.com/a ticles/css-
modules to de ne custom, e uni ue CSS class names fo
us. The e is nothing magical about CSS modules othe than it
fo ces ou build-tool to de ne custom CSS class names fo us
so e can o k ith less uni ue names. We'll look into using
CSS modules a bit late in ou o k o .
Orange header
76
78. React p o ides a not-so-ne method fo a oiding this p oblem enti el b
allo ing us to de ne st les inline along ith ou JSX.
Adding st les to ou actual components not onl allo us to de ne the st les
inside ou components, but allo us to d namicall de ne st les based upon
diffe ent states of the app.
React gi es us a a to de ne st les using a Ja aSc ipt object athe than a
sepa ate CSS le. Let's take ou Header component one mo e time and
instead of using css classes to de ne the st le, let's mo e it to inline st les.
De ning st les inside a component is eas using the style p op. All DOM
elements inside React accept a style p ope t , hich is e pected to be an
object ith camel-cased ke s de ning a st le name and alues hich map to
thei alue.
Fo e ample, to add a color st le to a <div /> element in JSX, this might
look like:
const style = { color: 'blue' }
<div style={style}>
This text will have the color blue
</div>
Inline styles
This text will have the color blue
77
79. Notice that e de ned the st les ith t o b aces
su ounding it. As e a e passing a Ja aSc ipt object ithin a
template tag, the inne b ace is the JS object and the oute is
the template tag.
Another e ample to possibl make this clearer ould be to pass a
Ja aScript object defined outside of the JSX, i.e.
render() {
const divStyle = { color: 'blue' }
return (<div style={divStyle}>
This text will have the color blue
</div>);
}
In an case, as these a e JS-de ned st les, so e can't use just an ole' css
st le name as background-color ould be in alid in Ja aSc ipt . Instead,
React e ui es us to camel-case the st le name.
camelCase https://en. ikipedia.o g/ iki/CamelCase is
iting compound o ds using a capital lette fo e e o d
ith a capital lette e cept fo the st o d, like
backgroundColor and linearGradient .
To update ou heade component to use these st les instead of depending on
a CSS class de nition, e can add the className p op along ith a style
p op:
78
80. class Header extends React.Component {
// ...
render() {
// Classes to add to the <input /> element
let searchInputClasses = ["searchInput"];
// Update the class array if the state is visible
if (this.state.searchVisible) {
searchInputClasses.push("active");
}
const wrapperStyle = {
backgroundColor: 'rgba(251, 202, 43, 1)'
}
const titleStyle = {
color: '#111111'
}
const menuColor = {
backgroundColor: '#111111'
}
return (
<div style={wrapperStyle} className="header">
<div className="menuIcon">
<div className="dashTop" style={menuColor}></div>
<div className="dashBottom" style={menuColor}></div>
<div className="circle" style={menuColor}></div>
</div>
<span style={titleStyle} className="title">
{this.props.title}
</span>
<input
type="text"
className={searchInputClasses.join(' ')}
placeholder="Search ..." />
{/* Adding an onClick handler to call the showSearch button
*/}
79
81. <div
style={titleStyle}
onClick={this.showSearch.bind(this)}
className="fa fa-search searchIcon"></div>
</div>
)
}
}
Ou heade ill be o ange again.
The React communit is a p ett ib ant place hich is one of the easons it
is a fantastic lib a to o k ith . The e a e a lot of st ling lib a ies e can
use to help us build ou st les, such as Radium
https://fo midable.com/open-sou ce/ adium/ b Fo midable labs.
Most of these lib a ies a e based upon o k o s de ned b React
de elope s th ough o king ith React.
Radium allo s us to de ne common st les outside of the React component
itself, it auto- endo p e es, suppo ts media ue ies like :hover and
:active , simpli es inline st ling, and kind of a lot mo e.
We on't di e into Radium in this post as it's mo e outside the scope of this
se ies, but kno ing othe lib a ies a e good to be a a e of, especiall if
ou' e looking to e tend the de nitions of ou inline st les.
Styling libraries
Orange header
80
82. No that e kno ho to st le ou components, e can make some good
looking ones ithout too much t ouble. In the ne t section, e'll get ight
back to adding use inte acti it to ou components.
81
83. Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/day-10/post.md)
Interactivity
Today e'll alk through ho to add interacti ity to our
applications to make them engaging and dynamic.
Th ough this point, e' e built ou fe handful of components ithout
adding much use inte action. Toda , e' e going to change that.
The b o se is an e ent-d i en application. E e thing that a use does in
the b o se es an e ent, f om clicking buttons to e en just mo ing the
mouse. In plain Ja aSc ipt, e can listen fo these e ents and attach a
Ja aSc ipt function to inte act ith them.
Fo instance, e can attach a function to the mousemove b o se e ent ith
the JS:
User interaction
82
84. export const go = () => {
const ele = document.getElementById('mousemove');
ele.innerHTML = 'Move your mouse to see the demo';
ele.addEventListener('mousemove', function(evt) {
const { screenX, screenY } = evt;
ele.innerHTML = '<div>Mouse is at: X: ' +
screenX + ', Y: ' + screenY +
'</div>';
})
}
This esults in the follo ing functionalit :
Move your mouse over this text
In React, ho e e e don't ha e to inte act ith the b o se 's e ent loop in
a Ja aSc ipt as React p o ides a a fo us to handle e ents using props .
Fo instance, to listen fo the mousemove e ent f om the athe unimp essi e
demo abo e in React, e'll set the p op onMouseMove notice the camelcasing
of the e ent name .
<div onMouseMove={(evt) => console.log(evt)}>
Move the mouse over this text
</div>
React p o ides a lot of props e can set to listen fo diffe ent b o se
e ents, such as click, touch, d ag, sc oll, selection e ents, and man mo e
see the e ents https://facebook.github.io/ eact/docs/e ents.html
documentation fo a list of all of them .
83
85. To see some of these in action, the follo ing is a small demo of some of the
props e can pass on ou elements. Each te t element in the list set the
p op it lists. T pla ing a ound ith the list and seeing ho the e ents a e
called and handled ithin the element all e ents a e set on the te t, not the
list item :
We'll be using the onClick p op uite a bit all th oughout ou apps uite a
bit, so it's a good idea to be familia ith it. In ou acti it list heade , e
ha e a sea ch icon that e ha en't hooked up et to sho a sea ch bo .
The inte action e ant is to sho a sea ch <input /> hen ou use s click
on the sea ch icon. Recall that ou Header component is implemented like
this:
84
86. class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
searchVisible: false
}
}
// toggle visibility when run on the state
showSearch() {
this.setState({
searchVisible: !this.state.searchVisible
})
}
render() {
// Classes to add to the <input /> element
let searchInputClasses = ["searchInput"];
// Update the class array if the state is visible
if (this.state.searchVisible) {
searchInputClasses.push("active");
}
return (
<div className="header">
<div className="menuIcon">
<div className="dashTop"></div>
<div className="dashBottom"></div>
<div className="circle"></div>
</div>
<span className="title">
{this.props.title}
</span>
<input
type="text"
className={searchInputClasses.join(' ')}
placeholder="Search ..." />
85
87. {/* Adding an onClick handler to call the showSearch button
*/}
<div
onClick={this.showSearch.bind(this)}
className="fa fa-search searchIcon"></div>
</div>
)
}
}
When the use clicks on the <div className="fa fa-search searchIcon">
</div> element, e'll ant to un a function to update the state of the
component so the searchInputClasses object gets updated. Using the
onClick handle , this is p ett simple.
Let's make this component stateful it needs to t ack if the sea ch eld
should be sho ing o not . We can con e t ou component to be stateful
using the constructor() function:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
searchVisible: false
}
}
// ...
}
86
88. In Ja aScript, the constructor function is a function that runs hen an
object is created. It returns a reference to the Object function that
created the instance's prototype .
In plain English, a constructor function is the function that runs hen the
Ja aScript runtime creates a ne object. We'll use the constructor
method to set up instance ariables on the object as it runs right hen
the object is created.
When using the ES6 class s nta to create an object, e ha e to call the
super() method before an other method. Calling the super() function
calls the parent class's constructor() function. We'll call it ith the same
arguments as the constructor() function of our class is called ith.
When the use clicks on the button, e'll ant to update the state to sa that
the searchVisible ag gets updated. Since e'll ant the use to be able to
close/hide the <input /> eld afte clicking on the sea ch icon fo a second
time, e'll toggle the state athe than just set it to t ue.
Let's c eate this method to bind ou click e ent:
class Header extends React.Component {
// ...
showSearch() {
this.setState({
searchVisible: !this.state.searchVisible
})
}
// ...
}
Finall , e can attach a click handle using the onClick p op on the icon
element to call ou ne showSearch() method. The enti e updated sou ce fo
ou Header component looks like this:
What is a constructor function?
87
90. class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
searchVisible: false
}
}
// toggle visibility when run on the state
showSearch() {
this.setState({
searchVisible: !this.state.searchVisible
})
}
render() {
// Classes to add to the <input /> element
let searchInputClasses = ["searchInput"];
// Update the class array if the state is visible
if (this.state.searchVisible) {
searchInputClasses.push("active");
}
return (
<div className="header">
<div className="fa fa-more"></div>
<span className="title">
{this.props.title}
</span>
<input
type="text"
className={searchInputClasses.join(' ')}
placeholder="Search ..." />
{/* Adding an onClick handler to call the showSearch button
*/}
<div
onClick={this.showSearch.bind(this)}
89
91. className="fa fa-search searchIcon"></div>
</div>
)
}
}
T clicking on the sea ch icon and atch the input eld appea and
disappea the animation effect is handled b CSS animations .
Whene e e build a fo m in React, e'll use the input e ents offe ed b
React. Most notabl , e'll use the onSubmit() and onChange() p ops most
often.
Let's update ou sea ch bo demo to captu e the te t inside the sea ch eld
hen it updates. Whene e an <input /> eld has the onChange() p op set,
it ill call the function e ery time the field changes. When e click on it and
sta t t ping, the function ill be called.
Using this p op, e can captu e the alue of the eld in ou state.
Rathe than updating ou <Header /> component, let's c eate a ne child
component to contain a <form /> element. B mo ing the fo m-handling
esponsibilities to it's o n fo m, e can simplif the <Header /> code and e
can call up to the pa ent of the heade hen ou use submits the fo m this
is a usual React patte n .
Let's c eate a ne component e'll call SearchForm . This ne component is a
stateful component as e'll need to hold on to the alue of the sea ch input
t ack it as it changes :
Input events
90
92. class SearchForm extends React.Component {
// ...
constructor(props) {
super(props);
this.state = {
searchText: ''
}
}
// ...
}
No , e al ead ha e the HTML fo the fo m itten in the <Header />
component, so let's g ab that f om ou Header component and etu n it f om
ou SearchForm.render() function:
class SearchForm extends React.Component {
// ...
render() {
const { searchVisible } = this.state;
let searchClasses = ['searchInput']
if (searchVisible) {
searchClasses.push('active')
}
return (
<form className='header'>
<input
type="search"
className={searchClasses.join(' ')}
onChange={this.updateSearchInput.bind(this)}
placeholder="Search ..." />
<div
onClick={this.showSearch.bind(this)}
className="fa fa-search searchIcon"></div>
</form>
);
}
}
91
93. Notice that e lost the st les on ou <input /> eld. Since e no longe
ha e the searchVisible state in ou ne component, e can't use it to st le
the <input /> an longe . Ho e er, e can pass a p op f om ou Header
component that tells the SearchForm to ende the input as isible.
Let's de ne the searchVisible p op using PropTypes , of cou se and update
the render function to use the ne p op alue to sho o hide the sea ch
<input /> . We'll also set a default alue fo the isibilit of the eld to be
false since ou Header sho s/hides it nicel :
class SearchForm extends React.Component {
static propTypes = {
onSubmit: PropTypes.func.isRequired,
searchVisible: PropTypes.bool
}
// ...
}
No e ha e ou st les back on the <input /> element, let's add the
functionalit fo hen the use t pes in the sea ch bo , e'll ant to captu e
the alue of the sea ch eld. We can achie e this o k o b attaching the
onChange p op to the <input /> element and passing it a function to call
e e time the <input /> element is changed.
92
94. class SearchForm extends React.Component {
// ...
updateSearchInput(e) {
const val = e.target.value;
this.setState({
searchText: val
});
}
// ...
render() {
const { searchVisible } = this.state;
let searchClasses = ['searchInput']
if (searchVisible) {
searchClasses.push('active')
}
return (
<form className='header'>
<input
type="search"
className={searchClasses.join(' ')}
onChange={this.updateSearchInput.bind(this)}
placeholder="Search ..." />
<div
onClick={this.showSearch.bind(this)}
className="fa fa-search searchIcon"></div>
</form>
);
}
}
When e t pe in the eld, the updateSearchInput() function ill be called.
We'll keep t ack of the alue of the fo m b updating the state. In the
updateSearchInput() function, e can call di ectl to this.setState() to
update the state of the component.
93
95. The alue is held on the event object's ta get as
event.target.value .
class SearchForm extends React.Component {
// ...
updateSearchInput(e) {
const val = e.target.value;
this.setState({
searchText: val
});
}
// ...
}
94
96. We're creating hat's kno n as an uncontrolled component as e're not
setting the alue of the <input /> element. We can't pro ide an
alidation or post-processing on the input te t alue as it stands right
no .
If e ant to alidate the field or manipulate the alue of the <input />
component, e'll ha e to create hat is called a controlled component,
hich reall just means that e pass it a alue using the value prop. A
controlled component ersion's render() function ould look like:
class SearchForm extends React.Component {
render() {
return (
<input
type="search"
value={this.state.searchText}
className={searchInputClasses}
onChange={this.updateSearchInput.bind(this)}
placeholder="Search ..." />
);
}
}
As of no , e ha e no a to actuall submit the fo m, so ou use 's can't
eall sea ch. Let's change this. We'll ant to ap the <input /> component
in a <form /> DOM element so ou use s can p ess the ente ke to submit
the fo m. We can captu e the fo m submission b using the onSubmit p op
on the <form /> element.
Let's update the render() function to e ect this change.
Controlled vs. uncontrolled
95
97. class SearchForm extends React.Component {
// ...
submitForm(e) {
e.preventDefault();
const {searchText} = this.state;
this.props.onSubmit(searchText);
}
// ...
render() {
const { searchVisible } = this.props;
let searchClasses = ['searchInput']
if (searchVisible) {
searchClasses.push('active')
}
return (
<form onSubmit={this.submitForm.bind(this)}>
<input
type="search"
className={searchClasses.join(' ')}
onChange={this.updateSearchInput.bind(this)}
placeholder="Search ..." />
</form>
);
}
}
We immediately call event.preventDefault() on the
submitForm() function. This stops the b o se f om bubbling
the e ent up hich ould causes the default beha io of the
enti e page to eload the default function hen a b o se
submits a fo m .
No hen e t pe into the <input /> eld and p ess ente , the
submitForm() function gets called ith the e ent object.
96
98. So... g eat, e can submit the fo m and stuff, but hen do e actuall do the
sea ching? Fo demonst ation pu poses ight no , e'll pass the sea ch te t
up the pa ent-child component chain so the Header can decide hat to
sea ch.
The SearchForm component ce tainly doesn't kno hat it's
sea ching, so e'll ha e to pass the esponsibility up the
chain. We'll use this callback st ategy uite a bit.
In o de to pass the sea ch functionalit up the chain, ou SearchForm ill
need to accept a p op function to call hen the fo m is submitted. Let's
de ne a p op e'll call onSubmit that e can pass to ou SearchForm
component. Being good de elope s, e'll also add a default prop alue and a
propType fo this onSubmit function. Since e'll ant to make su e the
onSubmit() is de ned, e'll set the onSubmit p op to be a e ui ed p op:
class SearchForm extends React.Component {
static propTypes = {
onSubmit: PropTypes.func.isRequired,
searchVisible: PropTypes.bool
}
// ...
static defaultProps = {
onSubmit: () => {},
searchVisible: false
}
// ...
}
When the fo m is submitted, e can call this function di ectl f om the
props . Since e' e keeping t ack of the sea ch te t in ou state, e can call
the function ith the searchText alue in the state so the onSubmit()
function onl gets the alue and doesn't need to deal ith an e ent.
97
99. class SearchForm extends React.Component {
// ...
submitForm(event) {
// prevent the form from reloading the entire page
event.preventDefault();
// call the callback with the search value
this.props.onSubmit(this.state.searchText);
}
}
No , hen the use p esses ente e can call this onSubmit() function
passed in the props b ou Header component.
We can use this SearchForm component in ou Header component and pass
it the t o p ops e' e de ned searchVisible and onSubmit :
98
100. import React from 'react';
import SearchForm from './SearchFormWithSubmit'
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
searchVisible: false
}
}
// toggle visibility when run on the state
showSearch() {
this.setState({
searchVisible: !this.state.searchVisible
})
}
render() {
// Classes to add to the <input /> element
let searchInputClasses = ["searchInput"];
// Update the class array if the state is visible
if (this.state.searchVisible) {
searchInputClasses.push("active");
}
return (
<div className="header">
<div className="menuIcon">
<div className="dashTop"></div>
<div className="dashBottom"></div>
<div className="circle"></div>
</div>
<span className="title">
{this.props.title}
</span>
<SearchForm
searchVisible={this.state.searchVisible}
99
101. onSubmit={this.props.onSubmit} />
{/* Adding an onClick handler to call the showSearch button
*/}
<div
onClick={this.showSearch.bind(this)}
className="fa fa-search searchIcon"></div>
</div>
)
}
}
export default Header
No e ha e a sea ch fo m component e can use and euse ac oss ou app.
Of cou se, e' e not actuall sea ching an thing et. Let's that and
implement sea ch.
To implement sea ch in ou component, e'll ant to pass up the sea ch
esponsibilit one mo e le el f om ou Header component to a containe
component e'll call Panel .
Fi st things st, let's implement the same patte n of passing a callback to a
pa ent component f om ithin a child component f om the Panel containe
to the Header component.
On the Header component, let's update the propTypes fo a p op e'll de ne
as a p op called onSearch :
Implementing search
100
102. class Header extends React.Component {
// ...
}
Header.propTypes = {
onSearch: PropTypes.func
}
Inside the Header component's 'submitFo m ' function, call this onSearch()
p op e ill pass into it:
class Header extends React.Component {
// ...
submitForm(val) {
this.props.onSearch(val);
}
// ...
}
Header.propTypes = {
onSearch: PropTypes.func
}
Notice that ou i tual t ee looks like this:
<Panel>
<Header>
<SearchForm></SearchForm>
</Header>
</Panel>
When the <SearchForm /> is updated, it ill pass along it's a areness of
the search input's change to it's parent, the <Header /> , hen it ill pass
along up ards to the <Panel /> component. This method is very common
in React apps and pro ides a good set of functional isolation for our
components.
101
103. Back in ou Panel component e built on da 7, e'll pass a function to the
Header as the onSearch() p op on the Header . What e' e sa ing he e is
that hen the sea ch fo m has been submitted, e ant the sea ch fo m to
call back to the heade component hich ill then call to the Panel
component to handle the sea ch.
Since the Header component doesn't cont ol the content listing, the Panel
component does, e ha e to pass the esponsibilit one mo e le el up, as
e' e de ning he e.
In an case, ou Panel component is essentiall a cop of ou Content
component e p e iousl o ked on:
102
104. class Panel extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false, // <~ set loading to false
activities: data,
filtered: data,
}
}
componentDidMount() {this.updateData();}
componentWillReceiveProps(nextProps) {
// Check to see if the requestRefresh prop has changed
if (nextProps.requestRefresh !== this.props.requestRefresh) {
this.setState({loading: true}, this.updateData);
}
}
handleSearch = txt => {
if (txt === '') {
this.setState({
filtered: this.state.activities
})
} else {
const { activities } = this.state
const filtered = activities.filter(a => a.actor &&
a.actor.login.match(txt))
this.setState({
filtered
})
}
}
// Call out to github and refresh directory
updateData() {
this.setState({
loading: false,
activities: data
}, this.props.onComponentRefresh);
}
103
105. render() {
const {loading, filtered} = this.state;
return (
<div>
<Header
onSubmit={this.handleSearch}
title="Github activity" />
<div className="content">
<div className="line"></div>
{/* Show loading message if loading */}
{loading && <div>Loading</div>}
{/* Timeline item */}
{filtered.map((activity) => (
<ActivityItem
key={activity.id}
activity={activity} />
))}
</div>
</div>
)
}
}
Let's update ou state to include a searchFilter st ing, hich ill just be the
sea ching alue:
class Panel extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
searchFilter: '',
activities: []
}
}
}
104
106. In o de to actuall handle the sea ching, e'll need to pass a onSearch()
function to ou Header component. Let's de ne an onSearch() function in
ou Panel component and pass it off to the Header p ops in the render()
function:
class Panel extends React.Component {
// ...
// after the content has refreshed, we want to
// reset the loading variable
onComponentRefresh() {this.setState({loading: false});}
handleSearch(val) {
// handle search here
}
render() {
const {loading} = this.state;
return (
<div>
<Header
onSearch={this.handleSearch.bind(this)}
title="Github activity" />
<Content
requestRefresh={loading}
onComponentRefresh={this.onComponentRefresh.bind(this)}
fetchData={this.updateData.bind(this)} />
</div>
)
}
}
All e did he e as add a handleSearch() function and pass it to the heade .
No hen the use t pes in the sea ch bo , the handleSearch() function on
ou Panel component ill be called.
To actuall implement sea ch, e'll need to keep t ack of this st ing and
update ou updateData() function to take into account sea ch lte ing. Fi st,
let's set the searchFilter on the state. We can also fo ce the Content to
eload the data b setting loading to t ue, so e can do this in one step:
105
107. class Panel extends React.Component {
// ...
handleSearch(val) {
this.setState({
searchFilter: val,
loading: true
});
}
// ...
}
Lastl , let's update ou updateData() function to take search into account.
class SearchableContent extends React.Component {
// ...
this.setState({loading: true}, this.updateData);
// ...
}
Although this might look comple , it's actuall nea l identical to ou e isting
updateData() function ith the e ception of the fact that e updated ou
fetch() esult to call the filter() method on the json collection.
All the collection.filter() function does is un the function passed in fo
e e element and it lte s out the alues that etu n fals alues, keeping
the ones that etu n t uth ones. Ou sea ch function simpl looks fo a
match on the Github acti it 's actor.login the Github use to see if it
ege p-matches the searchFilter alue.
With the updateData() function updated, ou sea ch is complete.
T sea ching fo auser .
No e ha e a 3-la e app component that handles sea ch f om a nested
child component. We jumped f om beginne to inte mediate ith this post.
Pat ou self on the back. This as some heft mate ial. Make su e ou
unde stand this because e'll use these concepts e co e ed toda uite
often.
106
108.
In the ne t section, e'll jump out and look at building pure components.
107
109. Edit this page on Github (https://github.com/fullstackreact/30-days-of-react/blob/day-11/post.md)
Pure Components
React offers se eral different methods for creating components.
Today e'll talk about the final method of creating components,
the function stateless pure component.
We' e looked at a fe diffe ent a s to build eact components. One method
e left out up th ough this point is the stateless component/functional
method of building React components.
As e' e seen up th ough this point, e' e onl o ked th ough building
components using the React.Component and React.createClass() methods.
Fo mo e pe fo mance and simplicit , React also allo s us to c eate pu e,
stateless components using a no mal Ja aSc ipt function.
A Pure component can eplace a component that onl has a render function.
Instead of making a full-blo n component just to ende some content to the
sc een, e can c eate a pure one instead.
Pure components a e the simplest, fastest components e can ite. The
a e eas to ite, simple to eason about, and the uickest component e
can ite. Befo e e di e into why these a e bette , let's ite one, o heck a
couple!
108
110. // The simplest one
const HelloWorld = () => (<div>Hello world</div>);
// A Notification component
const Notification = (props) => {
const {level, message} = props;
const classNames = ['alert', 'alert-' + level]
return (
<div className={classNames}>
{message}
</div>
)
};
// In ES5
var ListItem = function(props) {
var handleClick = function(event) {
props.onClick(event);
};
return (
<div className="list">
<a
href="#"
onClick={handleClick}>
{props.children}
</a>
</div>
)
}
So the a e just functions, ight? Yep! Since the a e just functions, it's eall
eas to test using pu e Ja aSc ipt. The idea is that if React kno s the props
that a e sent into a component, it can be dete ministic in kno ing if it has to
e ende o not. The same p ops in e ual the same output i tual DOM.
In React, functional components a e called ith an a gument of props
simila to the React.Component const ucto class , hich a e the props it's
called ith as ell as ith the cu ent context of the component t ee.
109
111. Fo instance, let's sa e ant to e ite ou o iginal Timer component
using functional components as e ant to gi e ou use s a d namic a to
set thei o n clock st les 4 hou clock s. , diffe ent sepa ato s, ma be
the don't ant to displa the seconds, etc .
We can b eak up ou clock into multiple components he e e can use each
block of time as an indi idual component. We might b eak them up like so:
const Hour = (props) => {
let {hours} = props;
if (hours === 0) { hours = 12; }
if (props.twelveHours) { hours -= 12; }
return (<span>{hours}</span>)
}
const Minute = ({minutes}) => (<span>{minutes<10 && '0'}{minutes}
</span>)
const Second = ({seconds}) => (<span>{seconds<10 && '0'}{seconds}
</span>)
const Separator = ({separator}) => (<span>{separator || ':'}</span>)
const Ampm = ({hours}) => (<span>{hours >= 12 ? 'pm' : 'am'}</span>)
With these, e can place indi idual components as th ough the a e full-
blo n React components the a e :
<div>Minute: <Minute minutes={12} /></div>
<div>Second: <Second seconds={51} /></div>
Minute: 12
Second: 51
110
112. We can efacto ou clock component to accept a format st ing and b eak up
this st ing selecting onl the components ou use is inte ested in sho ing.
The e a e multiple a s e can handle this, like fo cing the logic into the
Clock component or e can c eate anothe stateless component that
accepts a fo mat st ing. Let's do that easie to test :
const Formatter = (props) => {
let children = props.format.split('').map((e, idx) => {
if (e === 'h') {
return <Hour key={idx} {...props} />
} else if (e === 'm') {
return <Minute key={idx} {...props} />
} else if (e === 's') {
return <Second key={idx} {...props} />
} else if (e === 'p') {
return <Ampm key={idx} {...props} />
} else if (e === ' ') {
return <span key={idx}> </span>;
} else {
return <Separator key={idx} {...props} />
}
});
return <span>{children}</span>;
}
This is a little ugl ith the key and {...props} thingie in the e. React gi es
us some helpe s fo mapping o e child en and taking ca e of handling the
uni ue key fo each child th ough the React.Children object.
The render() function of ou Clock component can be g eatl simplified
thanks to the Formatter component into this:
111
114. Not onl is ou Clock component much simple , but it's so much easie to
test. It also ill help us t ansition to using a data state t ee, like Flu /Redu
f ame o ks, but mo e on those late .
Ad antages to using functional components in React a e:
We can do a a ith the hea lifting of components, no const ucto ,
state, life-c cle madness, etc.
The e is no this ke o d i.e. no need to bind
P esentational components also called dumb components emphasize
UI o e business logic i.e. no state manipulation in the component
Encou ages building smalle , self-contained components
Highlights badl itten code fo bette efacto ing
FAST FAST FAST FAST FAST
The a e easy to euse
You might sa h not use a functional component? Well, some of the
disad antage of using a functional component a e some of the ad antages:
No life-c cle callback hooks
Limited functionalit
The e is no this ke o d
O e all, it's a eall good idea to t to p efe using functional components
o e thei hea ie React.Component cousins. When e get to talking about
data management in React, e'll see ho e can use these p esentational
components ith data as pu e props .
15:52:58 pm
Uhh... so why care?
113
115. Nice o k toda . We' e successfull achie ed React ank afte toda . We no
kno the three a s to make a React Component.
Tomo o , e'll get set up using/building React apps ith the package
management tool shipped b the React team: create-react-app .
114