React js
Fundamentals
About me
SARRAJ Khaireddine
Laravel & React Js software engineer, Team
lead at Edidact SA and freelancer at Fiverr
E-mail:
[email protected] Twitter: twitter.com/Acewings_sk
LinkedIn: linkedin.com/in/khaireddinesarraj-3220a1150
WWW: fiverr.com/share/NEwv0o
What is React js?
What is React js?
• Developed by Facebook
• React is a view layer library, not a framework like Backbone, Angular etc.
• You can't use React to build a fully-functional web app
Why was React js
developed?
Why was React js developed?
• Complexity of two-way data binding
• Bad UX from using "cascading updates" of DOM tree
• A lot of data on a page changing over time
• Complexity of Facebook's UI architecture
• Shift from MVC mentality
Who the Heck!! use
React js?
The Pros and Cons of
React js?
The Pros of using React js?
• Easy to understand what a component will • Uses full power of JS
render • Decoupling templates from logic does not
• Declarative code → predictable code rely on the templates’ primitive
abstractions, but uses full power of
• You don't really need to study JS in the view file in
JavaScript in displaying views
order to understand what the file does
• It's not hard to learn • No complex two-way data flow
• Uses simple one-way reactive data flow
• Easy to mix HTML and JS
• Easier to understand than two-way binding
• You do it already with template libraries (e.g.
Handlebars, Mustache, Underscore etc.) • Uses less code
The Pros of using React js?
• React is fast!
• Real DOM (Physical DOM) is slow.
• JavaScript is fast.
• Using virtual DOM*1 objects enables fast batch updates to real DOM, with great productivity gains over
frequent cascading updates of DOM tree.
• React dev tools
• React Chrome extension makes debugging so much easier.
• Server-side rendering
• React.renderToString() returns pure HTML.
1*The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the
“real” DOM by a library such as ReactDOM
The Cons of using React js?
• React is nothing but the view • No support for older browsers
• No events • React won't work with IE8
• No XHR
• There some polyfills / shims that help
• No data / models
• No promises • Building JSX requires some extra work
• No idea how to add all of the above • But most of the work is already done for you
• Very little info in the docs by react-tools and Babel
• Architectural annoyances
• No pre-defined good practice directory schema to
follow
Why should we
React js?
Why should we React js?
• Easy to read and understand views
• Concept of components is the future of web development
• If your page uses a lot of fast updating data or real time data – React is the way
to go
• Developing your app will become a lot faster
• Total Freedom on whatever you want to do and implements – you can go wild !!
Fundamentals
Most important terms in React?
Components
React Components
• Components are self-contained • React components implement a render() method that
reusable building blocks of web takes input data and returns what to display. This
example uses an XML-like syntax called JSX. Input data
application.
that is passed into the component can be accessed by
• React components are basically render() via this.props
just idempotent functions (same
input produces same output).
• They describe your UI at any point
in time, just like a server-rendered
app.
React Component Types
• Function, Arrow Function and Class Components
• The simplest way to define a component is to write a JavaScript
function →
• Most Use Cases: View only, stateless and simple logic
• You can also use an ES6 class to define a component →
• Most Use Cases: View and code logic, stateful and complex logic
• Finally the Arrow function syntax we all love
• Most Use Cases: View and logic, stateless / stateless and simple to
mid-complex logic
• Unlike regular functions, arrow functions do not have their own
this. The value of this inside an arrow function remains the same
throughout the lifecycle of the function and is always bound to the
value of this in the closest non-arrow parent function.
Component
Life Cycle
Component Life Cycle
+
Props and State
Props
• Passed down to component from parent
component and represents data for the
component accessed via this.props in a
class component or passed as argument
• Props value can be: String, Array, Object,
JSX, Boolean, Number or even a function
• Props can only be passed to components
in one way (parent to child)
• Props data is immutable (read-only)
State
• Represents internal state of the component • When a change in the state is made, state shouldn’t be modified
• Accessed via this.state directly. Instead, state updates should be made with a special
method called setState( ).
• When a component's state data changes, the rendered
markup will be updated by re-invoking render() method
• State is a special object that holds dynamic data, which
means that state can change over time and anytime based
on user actions or certain events.
• State is private and belongs only to its component where
defined, cannot be accessed from outside, but can be
passed to child components via props.
• State is initialized inside its component’s constructor
method.
Conditional Rendering
Conditional Rendering
• With React, we can create really dynamic applications using
conditional rendering. Conditional rendering is when we render
different UI elements or components based on some conditions.
This is similar to how conditions work in JavaScript. Conditional
rendering is another concept that facilitates this process.
• Types of conditional rendering:
• Logical AND (&&) operator
• If...else statement
• Using ternary ((condition)? ’option 1’ : ‘option 2’ ) operators
• Preventing Component from Rendering (returning null)
Conditional Rendering
Lists & keys
ES 6 Array
• An array is a homogenous collection of values. To simplify, an array is a collection of values of the same data type.
It is a user-defined type.
• Creating an Array dynamically with the help of Array.From() Method out of:
• Sets – [ 1, "some text", {…}, {…} ]
• Set* objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the
Set may only occur once; it is unique in the Set's collection.
• Another Array – [‘A’, ‘B’, ‘C’,’D’]
• Or with the array keys – Array(5).keys()
Filter
• One of the most common tasks when working with an array
is to create a new array that contains a subset of elements
of the original array. The JavaScript filter array function is
used to filter an array based on specified criteria.
• The filter() method creates an array filled with all array
elements that pass a test (provided by a function).
• filter() does not execute the function for empty array
elements.
• filter() does not change the original array.
Find
• The find() method returns the value of the array element
that passes a test (provided by a function).
• The method executes the function once for each element
present in the array:
• If it finds an array element where the function returns a
true value, find() returns the value of that array
element (and does not check the remaining values)
• Otherwise it returns undefined
• find() does not execute the function for empty array
elements.
• find() does not change the original array.
Map
• Sometimes, you need to take an array, transform its
elements, and include the results in a new array.
• Typically, you use a for loop to iterate over the elements,
transform each individual one, and push the results into a
new array.
• The map() method creates a new array populated with
the results of calling a provided function on every
element in the calling array
• The map() method calls the provided function once for
each element in an array, in order.
• map() does not execute the function for empty elements.
• map() does not change the original array.
Foreach
• Typically, when you want to execute a function on
every element of an array, you use a for loop
statement. forEach() does not mutate the array on
which it is called.
• The forEach() method do not necessary return a
result, but it execute an effect.
• The forEach() method calls a function once for each
element in an array, in order.
• forEach() is not executed for array elements without
values.
Handling Events
React Event handling
• Handling events with React elements is very similar to handling
events on DOM elements. There are some syntax differences: Events
always start with ”on<event>”, for example onClick, onMouseEnter,
onMouseLeave, onScroll, onDragStart, onDragStop, ….
• React events are named using camelCase, rather than lowercase.
• With JSX you pass a function as the event handler, rather than a
string.
• The problem with this syntax is that a different callback is created
each time the Button renders. In most cases, this is fine. However, if
this callback is passed as a prop to lower components, those
components might do an extra re-rendering. We generally
recommend binding in the constructor or using the class fields
syntax (arrow function Component), to avoid this sort of
performance problem.
Passing Arguments to
Event Handlers
• Inside a loop, it is common to want to pass an extra parameter to an event handler. For example, if id is the row ID,
either of the following would work:
• The above two lines are equivalent, and use arrow functions and Function.prototype.bind respectively..
• In both cases, the e argument representing the React event will be passed as a second argument after the ID. With an
arrow function, we have to pass it explicitly, but with bind any further arguments are automatically forwarded.
Synthetic Events
• Your event handlers will be passed instances of SyntheticEvent, a cross-browser wrapper around the browser’s native
event. It has the same interface as the browser’s native event, including stopPropagation() and preventDefault(),
except the events work identically across all browsers.
• Here, e is a synthetic event. React defines these
synthetic events according to the W3C spec, so you
don’t need to worry about cross-browser
compatibility. React events do not work exactly the
same as native events.
• When using React, you generally don’t need to call addEventListener to add listeners to a DOM element after it is
created. Instead, just provide a listener when the element is initially rendered.