SlideShare a Scribd company logo
AMINE EL HARRAK
SOFTWARE ENGINEER (FULL-STACK DEVELOPER) @SQLI
2017
REACTJS
AGENDA
ïĩ Introduction to REACT
ïĩ Requirement and tooling
ïĩ Installing react
ïĩ JSX
ïĩ REACT Ecosystem
ïĩ Component LifeCycle
ïĩ REACT COMPONENTS
ïĩ Components interacting
INTRODUCTION
REACTJS
Welcome to React.js
React.js is a JavaScript library developed by Facebook engineers.
Here are just a few of the reasons why people choose to program with React
Fast
Apps made in React can handle
complex updates and still feel quick
and responsive
Modular
Instead of writing large, dense files of
code, you can write many smaller,
reusable files. React's modularity can be
a beautiful solution to JavaScript's
maintainability problems
Scalable
Large programs that display a lot
of changing data are where
React performs best
Flexible
You can use React for interesting
projects that have nothing to do
with making a web app
Popular
While this reason has admittedly
little to do with React's quality,
the truth is that understanding
React will make you more
employable
REQUIREMENT !
REACTJS
Prior knowledge
No prior React knowledge is expected but if you are new to JavaScript please read more JS
then returning to React.
Tooling
Browser, IDE, Node Js, Console, Curiosity ...
INSTALLING REACT
REACTJS
INSTALLING REACT [SPA]
Create React App is the best way to starting building a new React single page application. It sets up your
development environment so that you can use the latest JavaScript features, provides a nice developer
experience, and optimizes your app for production.
ïķ npm install -g create-react-app
ïķ create-react-app hello-world
ïķ cd hello-world
ïķ npm start
Create React App doesn't handle backend logic or databases; it just creates a frontend build pipeline, so
you can use it with any backend you want. It uses webpack, Babel and ESLint under the hood, but
configures them for you.
INSTALLING REACT [AREA]
You don't need to rewrite your app to start using React.
We recommend adding React to a small part of your application, such an individual widget, so you can see
if it works well for your use case.
While React can be used without a build pipeline, we recommend setting it up so you can be more
productive. A modern build pipeline typically consists of :
ïĩ A package manager, such as Yarn or npm. It lets you take advantage of a vast ecosystem of third-party
packages, and easily install or update them.
ïĩ A bundler, such as webpack or Browserify. It lets you write modular code and bundle it together into
small packages to optimize load time.
ïĩ A compiler such as Babel. It lets you write modern JavaScript code that still works in older browsers.
INSTALLING REACT [AREA]
//To install React with Yarn, run // To install React with npm, run:
Both Yarn and npm download packages from the npm registry.
ïĩ Enabling ES6 and JSX
We recommend using React with Babel to let you use ES6 and JSX in your JavaScript code. ES6 is a set
of modern JavaScript features that make development easier, and JSX is an extension to the JavaScript
language that works nicely with React.
yarn init
yarn add react react-dom
npm init
npm install -- save react react-dom
Development and Production Versions
By default, React includes many helpful warnings. These warnings are very useful in
development. However, they make React larger and slower so you should make sure to use
the production version when you deploy the app.
ïĩ Create React App : If you use Create React App, npm run build will create an optimized
build of your app in the build folder.
ïĩ Webpack : Include both DefinePlugin and UglifyJsPlugin into your production Webpack
configuration as described in this guide.
ïĩ Browserify : Run Browserify with NODE_ENV environment variable set to production and
use UglifyJS as the last build step so that development-only code gets stripped out.
INSTALLING REACT [CDN]
ïĩ Using a CDN
If you don't want to use npm to manage client packages :
Minified and optimized production versions of React are available at:
To load a specific version of react and react-dom, replace 15 with the version number.
<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
<script src="https://unpkg.com/react@15/dist/react.min.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>
JSX
REACTJS
JSX
JSX is a syntax extension for JavaScript code looks a lot like HTML (not valid JavaScript
web browsers can't read it), It was written to be used with React.
If a JavaScript file contains JSX code, then that file will have to be compiled. That means that
before the file reaches a web browser, a JSX compiler will translate any JSX into regular
JavaScript.
ïĩ http://magic.reactjs.net/htmltojsx.htm
JSX
You can use the JSX directly with the Babel JavaScript library in the Development mode
just for test and not in production !
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
JSX vs JS ?
var jsVar = ‘<h1>Hello world</h1>’ //JS VARIABLE
var jsxVar = <h1>Hello world</h1> //JSX ELEMENTS
var product = <img src="images/product-id.jpg" alt=‘product-name" width="500px" height="500px" />
ATTRIBUTES IN JSX
Use JSX or JS ?
ïĩ In React, it's possible to write your component in pure JS like:
ïĩ But I think it's not very comfortable to write your HTML in this way. Luckily we can
write it in a JSX syntax (JavaScript extension) which let us write HTML inline:
render () { return <div>Hello {this.props.name}</div>; }
render () {
return React.createElement("div", null, "Hello ", this.props.name); }
Nested
If a JSX expression takes up more than one line, then you should wrap the multi-line
JSX expression in parentheses. This looks strange at first, but you get used to it:
Nested JSX expressions can be saved as variables, passed to functions, etc., just like non-
nested JSX expressions can!
var theGoogleLink =
(
<a href="https://www.google.com">
<h1> Click me I am Google </h1>
</a>
);
Nested
Best practices :
To make this more readable, you can use HTML-style line breaks and indentation :
<a href="https://www.google.net"><h1>Click me I am Google</h1></a>
<a href="https://www.google.net">
<h1>Click me I am Google</h1>
</a>
Nested
There's a rule that we haven't mentioned :
A JSX expression must have exactly one outermost element.
// This code is not valid 
var paragraphs =
(
<p>I am a paragraph.</p>
<p>I, too, am a paragraph.</p>
);
// This code will work fine 
var paragraphs =
(
<div id="i-am-the-outermost-element">
<p>I am a paragraph.</p>
<p>I, too, am a paragraph.</p>
</div>
);
REACT APPLICATIONS ARE MADE
OUT OF COMPONENTS NOT
TEMPLATES
REACTJS
What's a component?
A component is a small, reusable chunk of code that is responsible for one job. That job is often to
render some HTML.
The terms "component," "React component," and "component instance" all refer to the same thing.
React ecosystem
var React = require('react');
var ReactDOM = require('react-dom');
//or
import React from 'react‘;
import ReactDOM from 'react-dom';
ReactDOM.render( element, container, [callback] );
ReactDOM : several React-specific methods, all of which deal with the DOM in some way or another.
ReactDOM.render makes its first argument appear onscreen. But where on the screen should that first
argument appear? The first argument is appended to whatever element is selected by the second argument.
Returns a JavaScript object ( contains methods that you need in order to use React).
Component LifeCycle
Component render in action
Take a look at the code below. This code will create and render a new React component:
import React from 'react‘;
import ReactDOM from 'react-dom';
let ProductElement = React.createClass(
{
render: function () {
return (
<div>
<h1>{product.id}</h1>
<img src={product.image.src} alt={product.image.alt} width={product.width} />
</div>
);
}});
ReactDOM.render( <ProductElement />, document.getElementById('app') );
//import library
// Component
// Render
React Component
Calling React.createClass is the way to make a new component class.
When you make a new component class, you should store it in a variable so that you can use it later.
On line 4, notice that our component class is stored in a variable named MyComponentClass.
Component class variable names must begin with capital letters!
This adheres to the naming convention in which class names are written in UpperCamelCase. There are
technical reasons for it as well.
React Component
ïĩ An other Example with a class extends React.component
Reactdom Render
let Product = (
<div>
<img src="pics/pk-004.jpg" />
<h1>
BLEU DE CHANEL
</h1>
<article>
<strong> EAU DE PARFUM VAPORISATEUR </strong> L’ÃĐloge de la libertÃĐ
masculine dans un aromatique-boisÃĐ au sillage captivant. Un parfum intemporel,
anticonformiste, contenu dans un flacon d'un bleu ÃĐnigmatique. En savoir plus ,,,
</article>
</div>
);
ReactDOM.render(Product , document.getElementById('app') );
Updating the Rendered Element
React elements are immutable. Once you create an element, you can't change its children
or attributes. An element is like a single frame in a movie: it represents the UI at a certain
point in time.
With our knowledge so far, the only way to update the UI is to create a new element, and
pass it to ReactDOM.render().
The virtual dom
The virtual dom
React Only Updates What's Necessary
One special thing about ReactDOM.render is that it only updates DOM elements that have changed.
That means that if you render the exact same thing twice in a row, the second render will do nothing:
var title = <h1> BLEU DE CHANEL </h1>;
// This will add " BLEU DE CHANEL " to the screen:
ReactDOM.render(title, document.getElementById('app'));
// This won't do anything at all:
ReactDOM.render(title, document.getElementById('app'));
React Diff Algorith
Granular dom updates
React DOM compares the element and its children to the previous one,
and only applies the DOM updates necessary to bring the DOM to the
desired state.
You can verify by inspecting the last example with the browser tools:
COMPONENTS AND
ADVANCED JSX
REACTJS
MultilineUseMultilineJSXina
Component
import React from 'react‘;
import ReactDOM from 'react-dom';
let QuoteMaker = React.createClass({
render: function () {
return (
<blockquote>
<p>
The world is full of objects, more or less interesting; I do not wish to add any more.
</p>
<cite>
<a target="_blank"
href="http://my-link.com">
Douglas Huebler
</a>
</cite>
</blockquote>
);
}
});
ReactDOM.render( <QuoteMaker />, document.getElementById('app'));
Variable Attributes
Take a look at this JavaScript object named product :
let product =
{
id: 56,
name: ‘BLEU DE CHANEL ‘,
image: {
src:’pics/pk-004.jpg’,
width : ‘200px’
}
};
Variable Attributes
Use a JavaScript variable attribute in a Component
let Product = React.createClass({
render: function () {
return (
<div>
<h1>{product.image.name}</h1>
<img
src={product.image.src}
alt={product.image,alt}
width={product.image.width} />
</div>
);
}
});
ReactDOM.render(< Product />, document.getElementById('app'));
Put Logic in a Render Function
A render function must have a return statement.
However, that isn't all that it can have. Can also be a fine place to put simple calculations that need to
happen right before a component renders.
let Random = React.createClass({
// This should be in the render function:
var n = Math.floor(Math.random()*10+1);
render: function () {
return <h1>The number is {n}!</h1>;
}
});
Put Logic in a Render Function
//import library here
var friends = [
{
title: "Yummmmmmm",
src: "https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-monkeyweirdo.jpg"
},
{
title: "Hey Guys! Wait Up!",
src: "https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-earnestfrog.jpg"
},
{
title: "Yikes",
src: "https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-alpaca.jpg"
}
];
JavaScriptobject
// New component class starts here:
let Friend = React.createClass({
render: function () {
var friend = friends[0];
return (
<div>
<h1>
{friend.title}
</h1>
<img src="{friend.src}"/>
</div>
);
}
});
ReactDOM.render(<Friend/>, document.getElementById('app'));
Put Logic in a Render Function
Component(Friend)
Conditional in a Render Function
//import library here !
let TodaysPlan = React.createClass({
render: function () {
var message;
var fiftyFifty = true;
if (!fiftyFifty) {
message = "out WOOO"
} else {
message = "to bed WOOO"
}
return <h1>Tonight I am going to {message}!</h1>;
}
});
ReactDOM.render(<TodaysPlan />, document.getElementById('app'));
Use this
The word this gets used in React a lot!
You are especially likely to see this inside of an object that is being passed to React.createClass.
let IceCreamGuy = React.createClass (
{
food: 'ice cream',
render: function () {
return <h1>I like {this.food}.</h1>;
}
}
);
Use this
In the code, what does this mean?
ïĩ this refers to the instructions object being passed to React.createClass.
ïĩ this has two properties: food, and render. this.food will evaluate to "ice cream."
There's nothing React-specific about this behaving in this way! However, in React you will see
this used in this way almost constantly.
If you aren't totally comfortable with this in JavaScript, here is a good resource.
Events Listener
Use an Event Listener in a Component !
Render functions often contain event listeners. Here's an example of an event listener
in a render function :
React.createClass({
myFunc: function () {
alert('Stop it. Stop hovering.');
},
render: function () {
return (
<div onHover={this.myFunc}> </div>;
);
}
});
Function
Event Listener
COMPONENTS INTERACTING
REACTJS
COMPONENTS INTERACTING
A React application can contain dozens, or even hundreds, of components.
ïĩ Each component might be small and relatively unremarkable on its own. When combined, however,
they can form enormous, fantastically complex ecosystems of information.
ïĩ In other words, React apps are made out of components, but what makes React special isn't
components themselves. What makes React special is the ways in which components interact.
ïĩ This unit is an introduction to components interacting.
A Component in a Render Function
Here is a render function that returns an HTML-like JSX element:
You've seen render functions return <div></div>s, <p></p>s, and <h1></h1>s,
just like in the above example.
var Example = React.createClass({
render: function () {
return <h1>Hello world</h1>;
}
});
Composing Components
Render functions can also return another kind of JSX: [component instances]
In the above example, Crazy's render function returns an instance of the OMG component class. You
could say that Crazy renders an <OMG />.
let OMG = React.createClass({ render: function () { return <h1>Whooaa!</h1>; } });
let Crazy = React.createClass({ render: function () { return <OMG />; } });
Please use module.exports
Alright! You've learned how to use require to import a file into a different file.
But you don't want to import a whole file! NavBar.js isn't really what you're looking for. You just
want to the NavBar component class, so that you can render a <NavBar /> instance.
What you need is a way to import only a specific part of a file into another file.
The answer is something called module.exports. module.exports comes from Node.js's module
system, just like require does. module.exports and require are meant to be used together, and
you basically never see one without the other.
Here's how you use module.exports:
In one file, declare module.exports to be equal to an expression. It could be any expression you
want:
Example without (module.exports)
ProfilePage.js NavBar.js
var NavBar = require('./NavBar');
var ProfilePage = React.createClass({
render: function () {
return (
<div>
<NavBar />
<h1>All About Me!</h1>
<p>I like movies and blah blah blah blah blah</p>
<img src="https://s3.amazonaws.com/codecademy-
content/courses/React/react_photo-monkeyselfie.jpg" />
</div>
);
}
});
var NavBar = React.createClass({
render: function () {
var pages = ['home', 'blog', 'pics', 'bio', 'art', 'shop', 'about',
'contact'];
var navLinks = pages.map(function(page){
return (
<a href={'/' + page}>
{page}
</a>
);
});
return <nav>{navLinks}</nav>;
}
});
Example using (module.exports)
ProfilePage.js NavBar.js
var NavBar = require('./NavBar');
var ProfilePage = React.createClass({
render: function () {
return (
<div>
<NavBar />
<h1>All About Me!</h1>
<p>I like movies and blah blah blah blah blah</p>
<img src="https://s3.amazonaws.com/codecademy-
content/courses/React/react_photo-monkeyselfie.jpg" />
</div>
);
}
});
var NavBar = React.createClass({
render: function () {
var pages = ['home', 'blog', 'pics', 'bio', 'art', 'shop', 'about', 'contact'];
var navLinks = pages.map(function(page){
return (
<a href={'/' + page}>
{page}
</a>
);
});
return <nav>{navLinks}</nav>;
}
});
module.exports = NavBar;
Use the component Attributs
Passing prop to componenet a render !
import React from 'react‘;
import ReactDOM from 'react-dom';
var Greeting = React.createClass({
render: function () {
return <h1>Hi there, {this.props.firstName}!
</h1>;
}
});
// ReactDOM.render goes here:
ReactDOM.render(
<Greeting firstName='Amine' />,
document.getElementById('app')
);
Attributs (convert attrs component to json)
var PropsDisplayer = React.createClass({
render: function () {
var stringProps = JSON.stringify(this.props);
return (
<div>
<h1>CHECK OUT MY PROPS OBJECT</h1>
<h2>{stringProps}</h2>
</div>
);
}
});
// ReactDOM.render goes here:
ReactDOM.render(<PropsDisplayer myProp="Hello" name="Frarthur" town="Flundon" age={2} haunted={false}/>, document.getElementById('app'))
{"myProp":"Hello","name":"Frarthur","town":"Flundon","age":2,"haunted":false}
Include element with passing props
import React from 'react‘;
import ReactDOM from 'react-dom';
var App = React.createClass({
render: function () {
return (
<div>
<h1>
<Greeting name={this.props.name} />
</h1>
<article>
Latest newzz: where is my phone?
</article>
</div>
);
}
});
ReactDOM.render(
<App name="aminem9" />,
document.getElementById('app')
);
import React from 'react‘;
var Greeting = React.createClass({
render: function () {
return <h1>Hi there, {this.props.name}!</h1>;
}
});
module.exports = Greeting;.
Default props value !
Impot ,,,
var Button = React.createClass({
???
render: function () {
return (
<button>
{this.props.text}
</button>
);
}
});
ReactDOM.render(
<Button text="" />,
document.getElementById('app')
);
getDefaultProps: function () {
return { text: 'I am a button' };
},
REACTJS
DYNAMIC INFORMATION
IN REACT
Dynamic information in React
There are two ways for a component to get dynamic information: props and state.
Besides props and state, everything in a component should always stay exactly the same.
You just spent a long lesson learning about props.
Now it's time to learn about state. props and state are all that you need to set up an ecosystem of
interacting React components.
The state
To read a component's state, use the expression this.state.name-of-property:
The above component class reads a property in its state from inside of its render function.
Just like this.props, you can use this.state from any property on the instructions object.
{this.state.myProperty}
getInitialState !
import React from 'react‘;
import ReactDOM from 'react-dom';
var App = React.createClass({
getInitialState: function () {
return { title: 'Best App' };
},
render: function () {
return (
<h1>{this.state.title}</h1>
);
}
});
ReactDOM.render(<App />,
document.getElementById('app')
)
A component can do more than just read its own state. A component can also change its own state.
A component changes its state by calling the function this.setState.
this.setState takes two arguments: an object that will update the component's state, and a callback. You
basically never need the callback.
In the code editor, take a look at Example.js. Notice that <Example /> has a state of:
var Example = React.createClass({
getInitialState: function () {
this.setState(
{
hungry: true
}
);
return {
mood: 'great',
hungry: false
};
},
render: function () {
return <div>{this.state.hungry}</div>;
}
});
<Example />
Set a state
Call this.setState from Another Function
import React from 'react‘;
import ReactDOM from 'react-dom';
var Mood = React.createClass({
getInitialState: function () {
return {
mood: 'good',
color: 'yellow'
};
},
changeColor: function () {
var newColor = this.state.color == 'yellow' ? 'green' : 'yellow';
this.setState({ color: newColor });
},
Call this.setState from Another Function
toggleMood: function () {
var newMood = this.state.mood == 'good' ? 'bad' : 'good';
this.setState({ mood: newMood });
},
render: function () {
return (
<div>
<h1>I'm feeling {this.state.mood}!</h1>
<button onClick={this.toggleMood}>
Click Me
</button>
</div>
);
}
});
ReactDOM.render(<Mood />, document.getElementById('app'));
Build a Stateful Component Class
import React from 'react‘;
import ReactDOM from 'react-dom';
var Header = React.createClass({
getInitialState: function() {
return {
imageSource: "mypicture.png"
};
},
changeImage: function() {
this.setState({imageSource: "differentpicture.png"});
},
render: function() {
return(
<img src={this.state.imageSource} onClick={this.changeImage.bind(this)} />
);
}
});
module.exports = Header;
Build a Stateless Component Class
import React from 'react‘;
import ReactDOM from 'react-dom';
var Header = React.createClass({
render: function() {
return(
<img src={this.props.imageSource} />
);
}
});
ReactDOM.render(<Header imageSource="myImage.png"/>, document.body);
property vs state react
https://github.com/uberVU/react-guide/blob/master/props-vs-state.md
Thank you !
UI = f (state)

More Related Content

PPTX
Introduction to React JS
Arnold Asllani
 
PDF
React js
Rajesh Kolla
 
PDF
ReactJS presentation
Thanh Tuong
 
PPTX
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
PPTX
Introduction to React JS for beginners
Varun Raj
 
PPTX
Introduction to react_js
MicroPyramid .
 
PPTX
Introduction to React JS for beginners | Namespace IT
namespaceit
 
PPTX
[Final] ReactJS presentation
æīŠ éđå‘
 
Introduction to React JS
Arnold Asllani
 
React js
Rajesh Kolla
 
ReactJS presentation
Thanh Tuong
 
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
Introduction to React JS for beginners
Varun Raj
 
Introduction to react_js
MicroPyramid .
 
Introduction to React JS for beginners | Namespace IT
namespaceit
 
[Final] ReactJS presentation
æīŠ éđå‘
 

What's hot (20)

PPTX
Reactjs
Neha Sharma
 
PPTX
Its time to React.js
Ritesh Mehrotra
 
PPTX
ReactJS presentation.pptx
DivyanshGupta922023
 
PPTX
Intro to React
Justin Reock
 
PPTX
React workshop
Imran Sayed
 
PDF
React JS - Introduction
Sergey Romaneko
 
PPTX
reactJS
Syam Santhosh
 
PDF
An introduction to React.js
Emanuele DelBono
 
PPTX
Introduction to React
Rob Quick
 
PPTX
ReactJs
Sahana Banerjee
 
ODP
Introduction to ReactJS
Knoldus Inc.
 
PPTX
React JS: A Secret Preview
valuebound
 
PPTX
React js
Oswald Campesato
 
PPTX
Introduction to Node.js
Vikash Singh
 
PPTX
Intro to React
Eric Westfall
 
PDF
Introduction to React JS
Bethmi Gunasekara
 
PPTX
React js programming concept
Tariqul islam
 
PPTX
React workshop presentation
Bojan Golubović
 
PPTX
React hooks
Assaf Gannon
 
PPT
React js
Jai Santhosh
 
Reactjs
Neha Sharma
 
Its time to React.js
Ritesh Mehrotra
 
ReactJS presentation.pptx
DivyanshGupta922023
 
Intro to React
Justin Reock
 
React workshop
Imran Sayed
 
React JS - Introduction
Sergey Romaneko
 
reactJS
Syam Santhosh
 
An introduction to React.js
Emanuele DelBono
 
Introduction to React
Rob Quick
 
ReactJs
Sahana Banerjee
 
Introduction to ReactJS
Knoldus Inc.
 
React JS: A Secret Preview
valuebound
 
React js
Oswald Campesato
 
Introduction to Node.js
Vikash Singh
 
Intro to React
Eric Westfall
 
Introduction to React JS
Bethmi Gunasekara
 
React js programming concept
Tariqul islam
 
React workshop presentation
Bojan Golubović
 
React hooks
Assaf Gannon
 
React js
Jai Santhosh
 
Ad

Viewers also liked (20)

PPTX
Getting started with typescript
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
PDF
React JS and why it's awesome
Andrew Hull
 
PDF
Power Leveling your TypeScript
Offirmo
 
PPTX
A Brief Introduction to React.js
Doug Neiner
 
PPTX
React + Redux Introduction
Nikolaus Graf
 
PDF
TypeScript: coding JavaScript without the pain
Sander Mak (@Sander_Mak)
 
PPTX
Internal workshop react-js-mruiz
Miguel Ruiz Rodriguez
 
PDF
React redux workshop
Daniel Ochoa John
 
PPTX
ReactJs presentation
nishasowdri
 
PDF
React Performance
Max Kudla
 
PPTX
Introduction to Facebook React
Mitch Chen
 
PDF
Discover React
Massimo Iacolare
 
PPTX
JavaScript뙀 TypeScriptė˜ ėœžëĶŽ ėžˆëŠ” 만ë‚Ļ
ė˜ėšą ęđ€
 
PDF
ėĩœí˜ļ똁, TYPESCRIPT - Javascriptė˜ ė•ˆė •ė„ąė„ 높ėīęļ° ėœ„í•œ ė‹œë„, NDC2013
devCAT Studio, NEXON
 
PDF
Intro to ReactJS
Harvard Web Working Group
 
PPT
How to solve daily, chronic problems in your business with concepts from Poly...
Redbox Studio
 
PDF
āļŠāļĢāđ‰āļēāļ‡āļ‹āļ­āļŸāļ•āđŒāđāļ§āļĢāđŒāļ­āļĒāđˆāļēāļ‡āđ„āļĢāđƒāļŦāđ‰āđ‚āļ”āļ™āđƒāļˆāļœāļđāđ‰āļ„āļ™ (How to make software that people love)
Kobkrit Viriyayudhakorn
 
PDF
React Webinar With CodePolitan
Riza Fahmi
 
PDF
Architecting for Enterprise with JavaScript
Kurtis Kemple
 
Getting started with typescript
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
React JS and why it's awesome
Andrew Hull
 
Power Leveling your TypeScript
Offirmo
 
A Brief Introduction to React.js
Doug Neiner
 
React + Redux Introduction
Nikolaus Graf
 
TypeScript: coding JavaScript without the pain
Sander Mak (@Sander_Mak)
 
Internal workshop react-js-mruiz
Miguel Ruiz Rodriguez
 
React redux workshop
Daniel Ochoa John
 
ReactJs presentation
nishasowdri
 
React Performance
Max Kudla
 
Introduction to Facebook React
Mitch Chen
 
Discover React
Massimo Iacolare
 
JavaScript뙀 TypeScriptė˜ ėœžëĶŽ ėžˆëŠ” 만ë‚Ļ
ė˜ėšą ęđ€
 
ėĩœí˜ļ똁, TYPESCRIPT - Javascriptė˜ ė•ˆė •ė„ąė„ 높ėīęļ° ėœ„í•œ ė‹œë„, NDC2013
devCAT Studio, NEXON
 
Intro to ReactJS
Harvard Web Working Group
 
How to solve daily, chronic problems in your business with concepts from Poly...
Redbox Studio
 
āļŠāļĢāđ‰āļēāļ‡āļ‹āļ­āļŸāļ•āđŒāđāļ§āļĢāđŒāļ­āļĒāđˆāļēāļ‡āđ„āļĢāđƒāļŦāđ‰āđ‚āļ”āļ™āđƒāļˆāļœāļđāđ‰āļ„āļ™ (How to make software that people love)
Kobkrit Viriyayudhakorn
 
React Webinar With CodePolitan
Riza Fahmi
 
Architecting for Enterprise with JavaScript
Kurtis Kemple
 
Ad

Similar to Learn react-js (20)

PDF
Learn react by Etietop Demas
Etietop Demas
 
PPTX
Reactjs notes.pptx for web development- tutorial and theory
jobinThomas54
 
PDF
Review on React JS
ijtsrd
 
PPTX
React_Complete.pptx
kamalakantas
 
PDF
Getting Started with React, When You’re an Angular Developer
Fabrit Global
 
PDF
learning react
Eueung Mulyana
 
PPTX
ReactJS.pptx
SamyakShetty2
 
PDF
react hook and wesite making structure ppt
arunkumarn100
 
PPTX
Unit 2 Fundamentals of React -------.pptx
krishitajariwala72
 
PDF
react.pdf
yihunie2
 
PDF
0900 learning-react
RohitYadav696
 
PPT
ReactJS.ppt
MOMEKEMKUEFOUETDUREL
 
PDF
Learning React js Learn React JS From Scratch with Hands On Projects 2nd Edit...
bandmvh3697
 
PDF
Reactjs Basics
Hamid Ghorbani
 
PPTX
React.js - The Dawn of Virtual DOM
Jimit Shah
 
PDF
Tech Talk on ReactJS
Atlogys Technical Consulting
 
PDF
Full Stack React Workshop [CSSC x GDSC]
GDSC UofT Mississauga
 
PDF
Fundamental concepts of react js
StephieJohn
 
PPTX
NEXTjs.pptxfggfgfdgfgfdgfdgfdgfdgfdgfdgfg
zmulani8
 
PPTX
GDG Workshop on React (By Aakanksha Rai)
gdgoncampuslncts
 
Learn react by Etietop Demas
Etietop Demas
 
Reactjs notes.pptx for web development- tutorial and theory
jobinThomas54
 
Review on React JS
ijtsrd
 
React_Complete.pptx
kamalakantas
 
Getting Started with React, When You’re an Angular Developer
Fabrit Global
 
learning react
Eueung Mulyana
 
ReactJS.pptx
SamyakShetty2
 
react hook and wesite making structure ppt
arunkumarn100
 
Unit 2 Fundamentals of React -------.pptx
krishitajariwala72
 
react.pdf
yihunie2
 
0900 learning-react
RohitYadav696
 
ReactJS.ppt
MOMEKEMKUEFOUETDUREL
 
Learning React js Learn React JS From Scratch with Hands On Projects 2nd Edit...
bandmvh3697
 
Reactjs Basics
Hamid Ghorbani
 
React.js - The Dawn of Virtual DOM
Jimit Shah
 
Tech Talk on ReactJS
Atlogys Technical Consulting
 
Full Stack React Workshop [CSSC x GDSC]
GDSC UofT Mississauga
 
Fundamental concepts of react js
StephieJohn
 
NEXTjs.pptxfggfgfdgfgfdgfdgfdgfdgfdgfdgfg
zmulani8
 
GDG Workshop on React (By Aakanksha Rai)
gdgoncampuslncts
 

Recently uploaded (20)

PDF
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
PPTX
Azure-DevOps-Training presentation downloadable
NamanGoyal428595
 
PPTX
Fluid Mechanics, Module 3: Basics of Fluid Mechanics
Dr. Rahul Kumar
 
PDF
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
PDF
Activated Carbon for Water and Wastewater Treatment_ Integration of Adsorptio...
EmilianoRodriguezTll
 
PDF
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
PDF
A Framework for Securing Personal Data Shared by Users on the Digital Platforms
ijcncjournal019
 
PPTX
TE-AI-Unit VI notes using planning model
swatigaikwad6389
 
PDF
Software Testing Tools - names and explanation
shruti533256
 
PPTX
Edge to Cloud Protocol HTTP WEBSOCKET MQTT-SN MQTT.pptx
dhanashri894551
 
PPTX
ANIMAL INTERVENTION WARNING SYSTEM (4).pptx
dodultrongaming
 
PPTX
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
PDF
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
PPTX
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
PDF
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
PPTX
EE3303-EM-I 25.7.25 electrical machines.pptx
Nagen87
 
PPTX
Unit 5 BSP.pptxytrrftyyydfyujfttyczcgvcd
ghousebhasha2007
 
PDF
5 Influence line.pdf for structural engineers
Endalkazene
 
PDF
Introduction to Data Science: data science process
ShivarkarSandip
 
PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
Azure-DevOps-Training presentation downloadable
NamanGoyal428595
 
Fluid Mechanics, Module 3: Basics of Fluid Mechanics
Dr. Rahul Kumar
 
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
Activated Carbon for Water and Wastewater Treatment_ Integration of Adsorptio...
EmilianoRodriguezTll
 
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
A Framework for Securing Personal Data Shared by Users on the Digital Platforms
ijcncjournal019
 
TE-AI-Unit VI notes using planning model
swatigaikwad6389
 
Software Testing Tools - names and explanation
shruti533256
 
Edge to Cloud Protocol HTTP WEBSOCKET MQTT-SN MQTT.pptx
dhanashri894551
 
ANIMAL INTERVENTION WARNING SYSTEM (4).pptx
dodultrongaming
 
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
EE3303-EM-I 25.7.25 electrical machines.pptx
Nagen87
 
Unit 5 BSP.pptxytrrftyyydfyujfttyczcgvcd
ghousebhasha2007
 
5 Influence line.pdf for structural engineers
Endalkazene
 
Introduction to Data Science: data science process
ShivarkarSandip
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 

Learn react-js

  • 1. AMINE EL HARRAK SOFTWARE ENGINEER (FULL-STACK DEVELOPER) @SQLI 2017 REACTJS
  • 2. AGENDA ïĩ Introduction to REACT ïĩ Requirement and tooling ïĩ Installing react ïĩ JSX ïĩ REACT Ecosystem ïĩ Component LifeCycle ïĩ REACT COMPONENTS ïĩ Components interacting
  • 4. Welcome to React.js React.js is a JavaScript library developed by Facebook engineers. Here are just a few of the reasons why people choose to program with React Fast Apps made in React can handle complex updates and still feel quick and responsive Modular Instead of writing large, dense files of code, you can write many smaller, reusable files. React's modularity can be a beautiful solution to JavaScript's maintainability problems Scalable Large programs that display a lot of changing data are where React performs best Flexible You can use React for interesting projects that have nothing to do with making a web app Popular While this reason has admittedly little to do with React's quality, the truth is that understanding React will make you more employable
  • 6. Prior knowledge No prior React knowledge is expected but if you are new to JavaScript please read more JS then returning to React.
  • 7. Tooling Browser, IDE, Node Js, Console, Curiosity ...
  • 9. INSTALLING REACT [SPA] Create React App is the best way to starting building a new React single page application. It sets up your development environment so that you can use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production. ïķ npm install -g create-react-app ïķ create-react-app hello-world ïķ cd hello-world ïķ npm start Create React App doesn't handle backend logic or databases; it just creates a frontend build pipeline, so you can use it with any backend you want. It uses webpack, Babel and ESLint under the hood, but configures them for you.
  • 10. INSTALLING REACT [AREA] You don't need to rewrite your app to start using React. We recommend adding React to a small part of your application, such an individual widget, so you can see if it works well for your use case. While React can be used without a build pipeline, we recommend setting it up so you can be more productive. A modern build pipeline typically consists of : ïĩ A package manager, such as Yarn or npm. It lets you take advantage of a vast ecosystem of third-party packages, and easily install or update them. ïĩ A bundler, such as webpack or Browserify. It lets you write modular code and bundle it together into small packages to optimize load time. ïĩ A compiler such as Babel. It lets you write modern JavaScript code that still works in older browsers.
  • 11. INSTALLING REACT [AREA] //To install React with Yarn, run // To install React with npm, run: Both Yarn and npm download packages from the npm registry. ïĩ Enabling ES6 and JSX We recommend using React with Babel to let you use ES6 and JSX in your JavaScript code. ES6 is a set of modern JavaScript features that make development easier, and JSX is an extension to the JavaScript language that works nicely with React. yarn init yarn add react react-dom npm init npm install -- save react react-dom
  • 12. Development and Production Versions By default, React includes many helpful warnings. These warnings are very useful in development. However, they make React larger and slower so you should make sure to use the production version when you deploy the app. ïĩ Create React App : If you use Create React App, npm run build will create an optimized build of your app in the build folder. ïĩ Webpack : Include both DefinePlugin and UglifyJsPlugin into your production Webpack configuration as described in this guide. ïĩ Browserify : Run Browserify with NODE_ENV environment variable set to production and use UglifyJS as the last build step so that development-only code gets stripped out.
  • 13. INSTALLING REACT [CDN] ïĩ Using a CDN If you don't want to use npm to manage client packages : Minified and optimized production versions of React are available at: To load a specific version of react and react-dom, replace 15 with the version number. <script src="https://unpkg.com/react@15/dist/react.js"></script> <script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script> <script src="https://unpkg.com/react@15/dist/react.min.js"></script> <script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>
  • 15. JSX JSX is a syntax extension for JavaScript code looks a lot like HTML (not valid JavaScript web browsers can't read it), It was written to be used with React. If a JavaScript file contains JSX code, then that file will have to be compiled. That means that before the file reaches a web browser, a JSX compiler will translate any JSX into regular JavaScript. ïĩ http://magic.reactjs.net/htmltojsx.htm
  • 16. JSX You can use the JSX directly with the Babel JavaScript library in the Development mode just for test and not in production ! <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
  • 17. JSX vs JS ? var jsVar = ‘<h1>Hello world</h1>’ //JS VARIABLE var jsxVar = <h1>Hello world</h1> //JSX ELEMENTS var product = <img src="images/product-id.jpg" alt=‘product-name" width="500px" height="500px" /> ATTRIBUTES IN JSX
  • 18. Use JSX or JS ? ïĩ In React, it's possible to write your component in pure JS like: ïĩ But I think it's not very comfortable to write your HTML in this way. Luckily we can write it in a JSX syntax (JavaScript extension) which let us write HTML inline: render () { return <div>Hello {this.props.name}</div>; } render () { return React.createElement("div", null, "Hello ", this.props.name); }
  • 19. Nested If a JSX expression takes up more than one line, then you should wrap the multi-line JSX expression in parentheses. This looks strange at first, but you get used to it: Nested JSX expressions can be saved as variables, passed to functions, etc., just like non- nested JSX expressions can! var theGoogleLink = ( <a href="https://www.google.com"> <h1> Click me I am Google </h1> </a> );
  • 20. Nested Best practices : To make this more readable, you can use HTML-style line breaks and indentation : <a href="https://www.google.net"><h1>Click me I am Google</h1></a> <a href="https://www.google.net"> <h1>Click me I am Google</h1> </a>
  • 21. Nested There's a rule that we haven't mentioned : A JSX expression must have exactly one outermost element. // This code is not valid  var paragraphs = ( <p>I am a paragraph.</p> <p>I, too, am a paragraph.</p> ); // This code will work fine  var paragraphs = ( <div id="i-am-the-outermost-element"> <p>I am a paragraph.</p> <p>I, too, am a paragraph.</p> </div> );
  • 22. REACT APPLICATIONS ARE MADE OUT OF COMPONENTS NOT TEMPLATES REACTJS
  • 23. What's a component? A component is a small, reusable chunk of code that is responsible for one job. That job is often to render some HTML. The terms "component," "React component," and "component instance" all refer to the same thing.
  • 24. React ecosystem var React = require('react'); var ReactDOM = require('react-dom'); //or import React from 'react‘; import ReactDOM from 'react-dom'; ReactDOM.render( element, container, [callback] ); ReactDOM : several React-specific methods, all of which deal with the DOM in some way or another. ReactDOM.render makes its first argument appear onscreen. But where on the screen should that first argument appear? The first argument is appended to whatever element is selected by the second argument. Returns a JavaScript object ( contains methods that you need in order to use React).
  • 26. Component render in action Take a look at the code below. This code will create and render a new React component: import React from 'react‘; import ReactDOM from 'react-dom'; let ProductElement = React.createClass( { render: function () { return ( <div> <h1>{product.id}</h1> <img src={product.image.src} alt={product.image.alt} width={product.width} /> </div> ); }}); ReactDOM.render( <ProductElement />, document.getElementById('app') ); //import library // Component // Render
  • 27. React Component Calling React.createClass is the way to make a new component class. When you make a new component class, you should store it in a variable so that you can use it later. On line 4, notice that our component class is stored in a variable named MyComponentClass. Component class variable names must begin with capital letters! This adheres to the naming convention in which class names are written in UpperCamelCase. There are technical reasons for it as well.
  • 28. React Component ïĩ An other Example with a class extends React.component
  • 29. Reactdom Render let Product = ( <div> <img src="pics/pk-004.jpg" /> <h1> BLEU DE CHANEL </h1> <article> <strong> EAU DE PARFUM VAPORISATEUR </strong> L’ÃĐloge de la libertÃĐ masculine dans un aromatique-boisÃĐ au sillage captivant. Un parfum intemporel, anticonformiste, contenu dans un flacon d'un bleu ÃĐnigmatique. En savoir plus ,,, </article> </div> ); ReactDOM.render(Product , document.getElementById('app') );
  • 30. Updating the Rendered Element React elements are immutable. Once you create an element, you can't change its children or attributes. An element is like a single frame in a movie: it represents the UI at a certain point in time. With our knowledge so far, the only way to update the UI is to create a new element, and pass it to ReactDOM.render().
  • 32. The virtual dom React Only Updates What's Necessary One special thing about ReactDOM.render is that it only updates DOM elements that have changed. That means that if you render the exact same thing twice in a row, the second render will do nothing: var title = <h1> BLEU DE CHANEL </h1>; // This will add " BLEU DE CHANEL " to the screen: ReactDOM.render(title, document.getElementById('app')); // This won't do anything at all: ReactDOM.render(title, document.getElementById('app')); React Diff Algorith
  • 33. Granular dom updates React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state. You can verify by inspecting the last example with the browser tools:
  • 35. MultilineUseMultilineJSXina Component import React from 'react‘; import ReactDOM from 'react-dom'; let QuoteMaker = React.createClass({ render: function () { return ( <blockquote> <p> The world is full of objects, more or less interesting; I do not wish to add any more. </p> <cite> <a target="_blank" href="http://my-link.com"> Douglas Huebler </a> </cite> </blockquote> ); } }); ReactDOM.render( <QuoteMaker />, document.getElementById('app'));
  • 36. Variable Attributes Take a look at this JavaScript object named product : let product = { id: 56, name: ‘BLEU DE CHANEL ‘, image: { src:’pics/pk-004.jpg’, width : ‘200px’ } };
  • 37. Variable Attributes Use a JavaScript variable attribute in a Component let Product = React.createClass({ render: function () { return ( <div> <h1>{product.image.name}</h1> <img src={product.image.src} alt={product.image,alt} width={product.image.width} /> </div> ); } }); ReactDOM.render(< Product />, document.getElementById('app'));
  • 38. Put Logic in a Render Function A render function must have a return statement. However, that isn't all that it can have. Can also be a fine place to put simple calculations that need to happen right before a component renders. let Random = React.createClass({ // This should be in the render function: var n = Math.floor(Math.random()*10+1); render: function () { return <h1>The number is {n}!</h1>; } });
  • 39. Put Logic in a Render Function //import library here var friends = [ { title: "Yummmmmmm", src: "https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-monkeyweirdo.jpg" }, { title: "Hey Guys! Wait Up!", src: "https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-earnestfrog.jpg" }, { title: "Yikes", src: "https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-alpaca.jpg" } ]; JavaScriptobject
  • 40. // New component class starts here: let Friend = React.createClass({ render: function () { var friend = friends[0]; return ( <div> <h1> {friend.title} </h1> <img src="{friend.src}"/> </div> ); } }); ReactDOM.render(<Friend/>, document.getElementById('app')); Put Logic in a Render Function Component(Friend)
  • 41. Conditional in a Render Function //import library here ! let TodaysPlan = React.createClass({ render: function () { var message; var fiftyFifty = true; if (!fiftyFifty) { message = "out WOOO" } else { message = "to bed WOOO" } return <h1>Tonight I am going to {message}!</h1>; } }); ReactDOM.render(<TodaysPlan />, document.getElementById('app'));
  • 42. Use this The word this gets used in React a lot! You are especially likely to see this inside of an object that is being passed to React.createClass. let IceCreamGuy = React.createClass ( { food: 'ice cream', render: function () { return <h1>I like {this.food}.</h1>; } } );
  • 43. Use this In the code, what does this mean? ïĩ this refers to the instructions object being passed to React.createClass. ïĩ this has two properties: food, and render. this.food will evaluate to "ice cream." There's nothing React-specific about this behaving in this way! However, in React you will see this used in this way almost constantly. If you aren't totally comfortable with this in JavaScript, here is a good resource.
  • 44. Events Listener Use an Event Listener in a Component ! Render functions often contain event listeners. Here's an example of an event listener in a render function : React.createClass({ myFunc: function () { alert('Stop it. Stop hovering.'); }, render: function () { return ( <div onHover={this.myFunc}> </div>; ); } }); Function Event Listener
  • 46. COMPONENTS INTERACTING A React application can contain dozens, or even hundreds, of components. ïĩ Each component might be small and relatively unremarkable on its own. When combined, however, they can form enormous, fantastically complex ecosystems of information. ïĩ In other words, React apps are made out of components, but what makes React special isn't components themselves. What makes React special is the ways in which components interact. ïĩ This unit is an introduction to components interacting.
  • 47. A Component in a Render Function Here is a render function that returns an HTML-like JSX element: You've seen render functions return <div></div>s, <p></p>s, and <h1></h1>s, just like in the above example. var Example = React.createClass({ render: function () { return <h1>Hello world</h1>; } });
  • 48. Composing Components Render functions can also return another kind of JSX: [component instances] In the above example, Crazy's render function returns an instance of the OMG component class. You could say that Crazy renders an <OMG />. let OMG = React.createClass({ render: function () { return <h1>Whooaa!</h1>; } }); let Crazy = React.createClass({ render: function () { return <OMG />; } });
  • 49. Please use module.exports Alright! You've learned how to use require to import a file into a different file. But you don't want to import a whole file! NavBar.js isn't really what you're looking for. You just want to the NavBar component class, so that you can render a <NavBar /> instance. What you need is a way to import only a specific part of a file into another file. The answer is something called module.exports. module.exports comes from Node.js's module system, just like require does. module.exports and require are meant to be used together, and you basically never see one without the other. Here's how you use module.exports: In one file, declare module.exports to be equal to an expression. It could be any expression you want:
  • 50. Example without (module.exports) ProfilePage.js NavBar.js var NavBar = require('./NavBar'); var ProfilePage = React.createClass({ render: function () { return ( <div> <NavBar /> <h1>All About Me!</h1> <p>I like movies and blah blah blah blah blah</p> <img src="https://s3.amazonaws.com/codecademy- content/courses/React/react_photo-monkeyselfie.jpg" /> </div> ); } }); var NavBar = React.createClass({ render: function () { var pages = ['home', 'blog', 'pics', 'bio', 'art', 'shop', 'about', 'contact']; var navLinks = pages.map(function(page){ return ( <a href={'/' + page}> {page} </a> ); }); return <nav>{navLinks}</nav>; } });
  • 51. Example using (module.exports) ProfilePage.js NavBar.js var NavBar = require('./NavBar'); var ProfilePage = React.createClass({ render: function () { return ( <div> <NavBar /> <h1>All About Me!</h1> <p>I like movies and blah blah blah blah blah</p> <img src="https://s3.amazonaws.com/codecademy- content/courses/React/react_photo-monkeyselfie.jpg" /> </div> ); } }); var NavBar = React.createClass({ render: function () { var pages = ['home', 'blog', 'pics', 'bio', 'art', 'shop', 'about', 'contact']; var navLinks = pages.map(function(page){ return ( <a href={'/' + page}> {page} </a> ); }); return <nav>{navLinks}</nav>; } }); module.exports = NavBar;
  • 52. Use the component Attributs Passing prop to componenet a render ! import React from 'react‘; import ReactDOM from 'react-dom'; var Greeting = React.createClass({ render: function () { return <h1>Hi there, {this.props.firstName}! </h1>; } }); // ReactDOM.render goes here: ReactDOM.render( <Greeting firstName='Amine' />, document.getElementById('app') );
  • 53. Attributs (convert attrs component to json) var PropsDisplayer = React.createClass({ render: function () { var stringProps = JSON.stringify(this.props); return ( <div> <h1>CHECK OUT MY PROPS OBJECT</h1> <h2>{stringProps}</h2> </div> ); } }); // ReactDOM.render goes here: ReactDOM.render(<PropsDisplayer myProp="Hello" name="Frarthur" town="Flundon" age={2} haunted={false}/>, document.getElementById('app')) {"myProp":"Hello","name":"Frarthur","town":"Flundon","age":2,"haunted":false}
  • 54. Include element with passing props import React from 'react‘; import ReactDOM from 'react-dom'; var App = React.createClass({ render: function () { return ( <div> <h1> <Greeting name={this.props.name} /> </h1> <article> Latest newzz: where is my phone? </article> </div> ); } }); ReactDOM.render( <App name="aminem9" />, document.getElementById('app') ); import React from 'react‘; var Greeting = React.createClass({ render: function () { return <h1>Hi there, {this.props.name}!</h1>; } }); module.exports = Greeting;.
  • 55. Default props value ! Impot ,,, var Button = React.createClass({ ??? render: function () { return ( <button> {this.props.text} </button> ); } }); ReactDOM.render( <Button text="" />, document.getElementById('app') ); getDefaultProps: function () { return { text: 'I am a button' }; },
  • 57. Dynamic information in React There are two ways for a component to get dynamic information: props and state. Besides props and state, everything in a component should always stay exactly the same. You just spent a long lesson learning about props. Now it's time to learn about state. props and state are all that you need to set up an ecosystem of interacting React components.
  • 58. The state To read a component's state, use the expression this.state.name-of-property: The above component class reads a property in its state from inside of its render function. Just like this.props, you can use this.state from any property on the instructions object. {this.state.myProperty}
  • 59. getInitialState ! import React from 'react‘; import ReactDOM from 'react-dom'; var App = React.createClass({ getInitialState: function () { return { title: 'Best App' }; }, render: function () { return ( <h1>{this.state.title}</h1> ); } }); ReactDOM.render(<App />, document.getElementById('app') )
  • 60. A component can do more than just read its own state. A component can also change its own state. A component changes its state by calling the function this.setState. this.setState takes two arguments: an object that will update the component's state, and a callback. You basically never need the callback. In the code editor, take a look at Example.js. Notice that <Example /> has a state of:
  • 61. var Example = React.createClass({ getInitialState: function () { this.setState( { hungry: true } ); return { mood: 'great', hungry: false }; }, render: function () { return <div>{this.state.hungry}</div>; } }); <Example /> Set a state
  • 62. Call this.setState from Another Function import React from 'react‘; import ReactDOM from 'react-dom'; var Mood = React.createClass({ getInitialState: function () { return { mood: 'good', color: 'yellow' }; }, changeColor: function () { var newColor = this.state.color == 'yellow' ? 'green' : 'yellow'; this.setState({ color: newColor }); },
  • 63. Call this.setState from Another Function toggleMood: function () { var newMood = this.state.mood == 'good' ? 'bad' : 'good'; this.setState({ mood: newMood }); }, render: function () { return ( <div> <h1>I'm feeling {this.state.mood}!</h1> <button onClick={this.toggleMood}> Click Me </button> </div> ); } }); ReactDOM.render(<Mood />, document.getElementById('app'));
  • 64. Build a Stateful Component Class import React from 'react‘; import ReactDOM from 'react-dom'; var Header = React.createClass({ getInitialState: function() { return { imageSource: "mypicture.png" }; }, changeImage: function() { this.setState({imageSource: "differentpicture.png"}); }, render: function() { return( <img src={this.state.imageSource} onClick={this.changeImage.bind(this)} /> ); } }); module.exports = Header;
  • 65. Build a Stateless Component Class import React from 'react‘; import ReactDOM from 'react-dom'; var Header = React.createClass({ render: function() { return( <img src={this.props.imageSource} /> ); } }); ReactDOM.render(<Header imageSource="myImage.png"/>, document.body);
  • 66. property vs state react https://github.com/uberVU/react-guide/blob/master/props-vs-state.md
  • 67. Thank you ! UI = f (state)

Editor's Notes

  • #63: stateful component you can also change the state, using this.setState
  • #65: stateful component you can also change the state, using this.setState
  • #66: Somewhere in the application, you need to bind data, or remember things. Stateless components are dumb (and that is good), they cannot remember and they cannot give context to other parts of the UI. Stateful components provide the necessary context glue. In the example above, you can see that during the render, imageSource is passed in as an attribute and is then added to the stateless components this.props object.