SlideShare a Scribd company logo
1 of 40
Download to read offline
React.JS
Enlightenment
Revisited
11-month story of me and ReactJS.
Artur Szott
@arturszott
11 months ago...
1 React
6 developers
. Frontend stack in the phase of research
Now
1 React
40 developers
8000+ commits within the frontend stack
React.js?
The V from the MVC.
The rest? M? C?
Checkbox.jsx
import React from 'react';
import { Input } from 'react-bootstrap';
class Checkbox extends React.Component {
render() {
return (
<Input
{...this.props}
type='checkbox'
labelClassName='formControl'
label={this.props.label}
/>
);
}
}
Checkbox.propTypes = {
label: React.PropTypes.string
};
export default Checkbox;
React views can consume some data
passed via props.
You can use any framework to render the react view.
import React from 'react';
import ReactDOM from 'react-dom';
import Checkbox from './Checkbox.jsx';
ReactDOM.render(<Checkbox label='meetJS' />, 'body');
Any
framework.
Brave people everywhere.
+
+
React reacts well with Flux...
Unidirectional application architecture.
...or one of the 15
flux implementations.
Math.floor((Math.random() * 15) + 1)
or check this helpful repo.
1. Facebook Flux
2. Fluxible by Yahoo
3. Reflux
4. Alt
5. Flummox
6. McFly
7. Lux
8. Material Flux
9. Redux
10. Redux + Flambeau
11. Nuclear.js
12. Fluxette
13. Fluxxor
14. Freezer
15. Your next great
flux implementation
Phases of
enlightenment
LEARNING CURVE IS A LIE.
DON’T TRUST PEOPLE OVER THE INTERNET.
1. Hatred.
But they said that React is awesome?
'awesome' !== 'easy';
People new to:
flux,
actions,
stores,
dispatchers,
props,
state,
lifecycle...
...will be lost.
./actions/updateImportantStatus.js
export default (context) => {
context.dispatch(UPDATE_IMPORTANT_STATUS, {
providerName: 'hc',
data: {
isAuthenticating: true
}
});
}
./components/LoginForm.jsx
import updateImportantStatus from '../actions/updateImportantStatus
class LoginForm extends BaseForm {
updateAuthenticationStatus() {
this.context.executeAction(updateImportantStatus);
}
render() {
return (
<form onSubmit={this.updateAuthenticationStatus.bind(this)}>
<Email ref='email' />
<Password ref='password'/>
<Checkbox ref='rememberMe' label=’Remember me’/>
<SubmitButton isBusy={this.props.isAuthenticating}> Login </SubmitButton>
</form>
);
}
}
Used to writing in
pure JS?
Say hello t0 JSX syntax
and ES6.
./components/pages/Login.jsx
class Login extends React.Component {
onValidationFailure(formErrors) {
const message = R.keys(formErrors).map((key) => {
return `${key}: ${formErrors[key]}`;
}).join(', ');
tracking.trackLoginFailure(this.context, { message });
}
render() {
return (
<div className='login-page-container'>
<FacebookScript appId={this.props.facebookAppId} />
<Page documentTitle='MeetJS Login' metaDescription='Hello MeetJS 2016!'>
<LoginForm ref='form'
isAuthenticating={this.props.isAuthenticating}
email={this.props.userEmail}
errorMessages={this.props.errorMessages}
onValidationFailure={this.onValidationFailure.bind(this)}
focusedElement={this.props.focusedElement}
/>
</Page>
</div>
);
}
}
2. Understanding.
I think I know what is happening there.
Knowing where to place my code
is definitely a big win.
- What to put inside the action?
- When to use props or state?
- Where to pour data into your app?
Old MVC habits can mislead you.
Treat the component like an instruction.
Components are the presentation of received data.
They can’t wait with executing callback after fired action.
3. Trust
I’m on the flow. My data is too.
One point of entry can be all you need.
Pass all necessary data at the top component and let the data
flow down the component tree, allowing child components
to align themselves.
Pass all “globals” at the top component.
PropTypes
are good for you.
Providing component
propTypes is one step
closer to build long
maintainable app.
./components/LoginForm.jsx
LoginForm.propTypes = {
isAuthenticating: React.PropTypes.bool,
email: React.PropTypes.string,
focusedElement: React.PropTypes.string,
errorMessages: React.PropTypes.shape({
password: React.PropTypes.string,
email: React.PropTypes.string
}),
onValidationSuccess: React.PropTypes.func,
onValidationFailure: React.PropTypes.func
};
You can always tell how component will
render based on the input
PropTypes are defining the input data of the component with
validation.
Warning: Failed propType: Required prop `appId` was
not specified in `FacebookScript`. Check the render method of `Login`.
Forgetting about propTypes definition is
not a problem with a little help
of eslint-react plugin.
5:50 error 'baseUrl' is missing in props validation react/prop-types
STACK EVOLUTION
IT’S A GOOD TIME TO START WRITING IN REACT,
BUT IT WASN’T ALWAYS THAT GOOD.
Before
So, you are using JSLint? Here comes JSX.
Now
You are using JSX? Here are the tools, pick some.
./test/unit/mocha.opts
--slow 5
--reporter dot
--recursive
--require ./test/unit/setup.js
--require ./test/throwOnWarnings.js
--compilers jsx:./test/babelCompiler.js
./package.json
"scripts": {
"test:unit": "NODE_ENV=test mocha test/unit --opts test/unit/mocha.opts"
}
command line:
npm run test:unit
Our working unit test
stack example.
./test/throwOnWarnings.js
const consoleError = console.error;
console.error = function (firstMessage, ...rest) {
if (firstMessage.startsWith('Warning:')) {
throw new Error(`Unexpected React Warning: ${firstMessage}`);
}
return consoleError(firstMessage, ...rest);
};
Never forget
about React warnings.
./test/throwOnWarnings.js
const hooks = require.extensions;
const extensions = Object.keys(hooks);
const limit = 15;
let count = 0;
extensions.forEach(function (extension) {
const originalHook = hooks[extension];
require.extensions[extension] = function (module, filename) {
if (filename.endsWith('node_modules/unwantedLibrary/index.js')) {
count += 1;
}
return originalHook(module, filename);
};
});
Made a mistake
in introducing
some lib?
./test/throwOnWarnings.js
process.on('exit', function () {
const diff = count - limit;
if (count > 0) {
console.log('Number of unwantedLibrary usages:', count);
}
if (diff > 0) {
throw new Error(
`The number of unwantedLibrary usages has been increased by ${diff}`
);
}
});
Restrict it usage!
Remove usages
and decrease
the limit over time.
CODE TESTABILITY
SOME CODE CAN BE TESTED WELL.
SOME CODE NOT, BUT IT’S NOT REACT’S FAULT.
Overriding dependencies is
a short win,
but in some time it will hit
you back.
Faster than you think.
Overriding deps. ./app/components/App.jsx
import isOnClient from '../lib/isOnClient';
./app/lib/isOnClient.js
export default function () {
return typeof document !== 'undefined';
}
./test/components/App.jsx
Application = proxyquire('../../../../app/components/Application', {
'../lib/isOnClient': () => true
});
Keeping the components small is the key.
Testing small component is a beautiful thing.
Isolating some parts of well determined behaviour allows you
to control the component only by changing input data and
testing the results.
Two ways of Reacting.
1. Stateless functions
Why? Simple.
./stateless/Header.jsx
import { detectSomething } from '../../lib/detectors';
const Header = (props) => {
const link = detectSomething(props.baseUrl) === 'meetJS'
? '/meetRegistration' : '/leave';
return (
<header>
<h1>Register</h1>
<a href={link} className='register-link'>Register now</a>
</header>
);
};
Two ways of Reacting.
2. Stateful components
Why? Extendable.
./stateful/Header.jsx
import { detectSomething } from '../../lib/detectors';
class Header extends React.Component {
render() {
const link = detectSomething(this.props.baseUrl) === 'meetJS'
? '/meetRegistration' : '/leave';
return (
<header>
<h1>Register</h1>
<a href={link} className='register-link'>Register now</a>
</header>
);
}
}
THE FUTURE OF
REACT
We have started knowing react when he was 0.13.0
Now he is 0.14.7 - what changed?
React is evolving.
He is kind enough not to break our code.
Every version introduces some changes, but they are well
described, showing developers that things will change.
This gave us some time, to remove more than 200 warnings
from our code, before version changed. Now we have 0.
React announced its stability.
In a strange way.
From the begining
people were expecting the final version 1.0.0
Surprise. We have now version 15.0.0.
SO… why we react?Artur Szott
@arturszott
Simplicity (after some trials and errors)
Testability (after learning finding good tools and setup)
Performance (haven’t encountered bottlenecks as fast as with backbone)
Bonus.
Inspire yourself by reading following articles:
Artur Szott
@arturszott
JSX looks like abomination, but it’s good for you.
https://medium.com/javascript-scene/jsx-looks-like-an-abomination-1c1ec351a918
9 things every React.js beginner should know
https://camjackson.net/post/9-things-every-reactjs-beginner-should-know
Using React is a Business Decision, Not a Technology Choice
https://blog.formidable.com/using-react-is-a-business-decision-not-a-technology-choice-
63c4641c5f7
The end.
You can work with me at HolidayCheck.
github.com/holidaycheck/jobs
Artur Szott
@arturszott
Photo: https://twitter.com/notbrent/status/696091475256352768 | Backgrounds: Unsplash.com

More Related Content

What's hot

Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It'sJim Lynch
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingLars Thorup
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testingjeresig
 
AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasminefoxp2code
 
Jasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyJasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyIgor Napierala
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsFITC
 
Testing JavaScript Applications
Testing JavaScript ApplicationsTesting JavaScript Applications
Testing JavaScript ApplicationsThe Rolling Scopes
 
Object Oreinted Approach in Coldfusion
Object Oreinted Approach in ColdfusionObject Oreinted Approach in Coldfusion
Object Oreinted Approach in Coldfusionguestcc9fa5
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Codescidept
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript TestingKissy Team
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Roy Yu
 
Dive into SObjectizer 5.5. Fourth part. Exception
Dive into SObjectizer 5.5. Fourth part. ExceptionDive into SObjectizer 5.5. Fourth part. Exception
Dive into SObjectizer 5.5. Fourth part. ExceptionYauheni Akhotnikau
 
Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Vysakh Sreenivasan
 

What's hot (18)

Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasmine
 
Jasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyJasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishy
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
Testing JavaScript Applications
Testing JavaScript ApplicationsTesting JavaScript Applications
Testing JavaScript Applications
 
Jasmine BDD for Javascript
Jasmine BDD for JavascriptJasmine BDD for Javascript
Jasmine BDD for Javascript
 
Object Oreinted Approach in Coldfusion
Object Oreinted Approach in ColdfusionObject Oreinted Approach in Coldfusion
Object Oreinted Approach in Coldfusion
 
node.js errors
node.js errorsnode.js errors
node.js errors
 
Thomas Fuchs Presentation
Thomas Fuchs PresentationThomas Fuchs Presentation
Thomas Fuchs Presentation
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101
 
Dive into SObjectizer 5.5. Fourth part. Exception
Dive into SObjectizer 5.5. Fourth part. ExceptionDive into SObjectizer 5.5. Fourth part. Exception
Dive into SObjectizer 5.5. Fourth part. Exception
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)
 

Similar to MeetJS Summit 2016: React.js enlightenment

20150516 modern web_conf_tw
20150516 modern web_conf_tw20150516 modern web_conf_tw
20150516 modern web_conf_twTse-Ching Ho
 
How to dispatch redux action with timeout
How to dispatch redux action with timeoutHow to dispatch redux action with timeout
How to dispatch redux action with timeoutBOSC Tech Labs
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS Components3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS ComponentsSurendra kumar
 
Server side rendering with React and Symfony
Server side rendering with React and SymfonyServer side rendering with React and Symfony
Server side rendering with React and SymfonyIgnacio Martín
 
Making React Native UI Components with Swift
Making React Native UI Components with SwiftMaking React Native UI Components with Swift
Making React Native UI Components with SwiftRay Deck
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practicesClickky
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxBOSC Tech Labs
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today Nitin Tyagi
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
React & The Art of Managing Complexity
React &  The Art of Managing ComplexityReact &  The Art of Managing Complexity
React & The Art of Managing ComplexityRyan Anklam
 
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3Rob Tweed
 
Ways to Set Focus on an Input Field After Rendering in React.pptx
Ways to Set Focus on an Input Field After Rendering in React.pptxWays to Set Focus on an Input Field After Rendering in React.pptx
Ways to Set Focus on an Input Field After Rendering in React.pptxBOSC Tech Labs
 
React for Re-use: Creating UI Components with Confluence Connect
React for Re-use: Creating UI Components with Confluence ConnectReact for Re-use: Creating UI Components with Confluence Connect
React for Re-use: Creating UI Components with Confluence ConnectAtlassian
 

Similar to MeetJS Summit 2016: React.js enlightenment (20)

Intro react js
Intro react jsIntro react js
Intro react js
 
20150516 modern web_conf_tw
20150516 modern web_conf_tw20150516 modern web_conf_tw
20150516 modern web_conf_tw
 
How to dispatch redux action with timeout
How to dispatch redux action with timeoutHow to dispatch redux action with timeout
How to dispatch redux action with timeout
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS Components3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS Components
 
Server side rendering with React and Symfony
Server side rendering with React and SymfonyServer side rendering with React and Symfony
Server side rendering with React and Symfony
 
Making React Native UI Components with Swift
Making React Native UI Components with SwiftMaking React Native UI Components with Swift
Making React Native UI Components with Swift
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practices
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptx
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today
 
Let's react - Meetup
Let's react - MeetupLet's react - Meetup
Let's react - Meetup
 
React lecture
React lectureReact lecture
React lecture
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
React native by example by Vadim Ruban
React native by example by Vadim RubanReact native by example by Vadim Ruban
React native by example by Vadim Ruban
 
React & The Art of Managing Complexity
React &  The Art of Managing ComplexityReact &  The Art of Managing Complexity
React & The Art of Managing Complexity
 
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3
EWD 3 Training Course Part 39: Building a React.js application with QEWD, Part 3
 
Ways to Set Focus on an Input Field After Rendering in React.pptx
Ways to Set Focus on an Input Field After Rendering in React.pptxWays to Set Focus on an Input Field After Rendering in React.pptx
Ways to Set Focus on an Input Field After Rendering in React.pptx
 
React for Re-use: Creating UI Components with Confluence Connect
React for Re-use: Creating UI Components with Confluence ConnectReact for Re-use: Creating UI Components with Confluence Connect
React for Re-use: Creating UI Components with Confluence Connect
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
 

Recently uploaded

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 

Recently uploaded (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

MeetJS Summit 2016: React.js enlightenment

  • 1. React.JS Enlightenment Revisited 11-month story of me and ReactJS. Artur Szott @arturszott
  • 2. 11 months ago... 1 React 6 developers . Frontend stack in the phase of research
  • 3. Now 1 React 40 developers 8000+ commits within the frontend stack
  • 4. React.js? The V from the MVC. The rest? M? C? Checkbox.jsx import React from 'react'; import { Input } from 'react-bootstrap'; class Checkbox extends React.Component { render() { return ( <Input {...this.props} type='checkbox' labelClassName='formControl' label={this.props.label} /> ); } } Checkbox.propTypes = { label: React.PropTypes.string }; export default Checkbox;
  • 5. React views can consume some data passed via props. You can use any framework to render the react view. import React from 'react'; import ReactDOM from 'react-dom'; import Checkbox from './Checkbox.jsx'; ReactDOM.render(<Checkbox label='meetJS' />, 'body');
  • 7. React reacts well with Flux... Unidirectional application architecture.
  • 8. ...or one of the 15 flux implementations. Math.floor((Math.random() * 15) + 1) or check this helpful repo. 1. Facebook Flux 2. Fluxible by Yahoo 3. Reflux 4. Alt 5. Flummox 6. McFly 7. Lux 8. Material Flux 9. Redux 10. Redux + Flambeau 11. Nuclear.js 12. Fluxette 13. Fluxxor 14. Freezer 15. Your next great flux implementation
  • 9. Phases of enlightenment LEARNING CURVE IS A LIE. DON’T TRUST PEOPLE OVER THE INTERNET.
  • 10. 1. Hatred. But they said that React is awesome? 'awesome' !== 'easy';
  • 11. People new to: flux, actions, stores, dispatchers, props, state, lifecycle... ...will be lost. ./actions/updateImportantStatus.js export default (context) => { context.dispatch(UPDATE_IMPORTANT_STATUS, { providerName: 'hc', data: { isAuthenticating: true } }); } ./components/LoginForm.jsx import updateImportantStatus from '../actions/updateImportantStatus class LoginForm extends BaseForm { updateAuthenticationStatus() { this.context.executeAction(updateImportantStatus); } render() { return ( <form onSubmit={this.updateAuthenticationStatus.bind(this)}> <Email ref='email' /> <Password ref='password'/> <Checkbox ref='rememberMe' label=’Remember me’/> <SubmitButton isBusy={this.props.isAuthenticating}> Login </SubmitButton> </form> ); } }
  • 12. Used to writing in pure JS? Say hello t0 JSX syntax and ES6. ./components/pages/Login.jsx class Login extends React.Component { onValidationFailure(formErrors) { const message = R.keys(formErrors).map((key) => { return `${key}: ${formErrors[key]}`; }).join(', '); tracking.trackLoginFailure(this.context, { message }); } render() { return ( <div className='login-page-container'> <FacebookScript appId={this.props.facebookAppId} /> <Page documentTitle='MeetJS Login' metaDescription='Hello MeetJS 2016!'> <LoginForm ref='form' isAuthenticating={this.props.isAuthenticating} email={this.props.userEmail} errorMessages={this.props.errorMessages} onValidationFailure={this.onValidationFailure.bind(this)} focusedElement={this.props.focusedElement} /> </Page> </div> ); } }
  • 13. 2. Understanding. I think I know what is happening there.
  • 14. Knowing where to place my code is definitely a big win. - What to put inside the action? - When to use props or state? - Where to pour data into your app?
  • 15. Old MVC habits can mislead you. Treat the component like an instruction. Components are the presentation of received data. They can’t wait with executing callback after fired action.
  • 16. 3. Trust I’m on the flow. My data is too.
  • 17. One point of entry can be all you need. Pass all necessary data at the top component and let the data flow down the component tree, allowing child components to align themselves. Pass all “globals” at the top component.
  • 18. PropTypes are good for you. Providing component propTypes is one step closer to build long maintainable app. ./components/LoginForm.jsx LoginForm.propTypes = { isAuthenticating: React.PropTypes.bool, email: React.PropTypes.string, focusedElement: React.PropTypes.string, errorMessages: React.PropTypes.shape({ password: React.PropTypes.string, email: React.PropTypes.string }), onValidationSuccess: React.PropTypes.func, onValidationFailure: React.PropTypes.func };
  • 19. You can always tell how component will render based on the input PropTypes are defining the input data of the component with validation. Warning: Failed propType: Required prop `appId` was not specified in `FacebookScript`. Check the render method of `Login`.
  • 20. Forgetting about propTypes definition is not a problem with a little help of eslint-react plugin. 5:50 error 'baseUrl' is missing in props validation react/prop-types
  • 21. STACK EVOLUTION IT’S A GOOD TIME TO START WRITING IN REACT, BUT IT WASN’T ALWAYS THAT GOOD.
  • 22. Before So, you are using JSLint? Here comes JSX.
  • 23. Now You are using JSX? Here are the tools, pick some.
  • 24. ./test/unit/mocha.opts --slow 5 --reporter dot --recursive --require ./test/unit/setup.js --require ./test/throwOnWarnings.js --compilers jsx:./test/babelCompiler.js ./package.json "scripts": { "test:unit": "NODE_ENV=test mocha test/unit --opts test/unit/mocha.opts" } command line: npm run test:unit Our working unit test stack example.
  • 25. ./test/throwOnWarnings.js const consoleError = console.error; console.error = function (firstMessage, ...rest) { if (firstMessage.startsWith('Warning:')) { throw new Error(`Unexpected React Warning: ${firstMessage}`); } return consoleError(firstMessage, ...rest); }; Never forget about React warnings.
  • 26. ./test/throwOnWarnings.js const hooks = require.extensions; const extensions = Object.keys(hooks); const limit = 15; let count = 0; extensions.forEach(function (extension) { const originalHook = hooks[extension]; require.extensions[extension] = function (module, filename) { if (filename.endsWith('node_modules/unwantedLibrary/index.js')) { count += 1; } return originalHook(module, filename); }; }); Made a mistake in introducing some lib?
  • 27. ./test/throwOnWarnings.js process.on('exit', function () { const diff = count - limit; if (count > 0) { console.log('Number of unwantedLibrary usages:', count); } if (diff > 0) { throw new Error( `The number of unwantedLibrary usages has been increased by ${diff}` ); } }); Restrict it usage! Remove usages and decrease the limit over time.
  • 28. CODE TESTABILITY SOME CODE CAN BE TESTED WELL. SOME CODE NOT, BUT IT’S NOT REACT’S FAULT.
  • 29. Overriding dependencies is a short win, but in some time it will hit you back. Faster than you think.
  • 30. Overriding deps. ./app/components/App.jsx import isOnClient from '../lib/isOnClient'; ./app/lib/isOnClient.js export default function () { return typeof document !== 'undefined'; } ./test/components/App.jsx Application = proxyquire('../../../../app/components/Application', { '../lib/isOnClient': () => true });
  • 31. Keeping the components small is the key. Testing small component is a beautiful thing. Isolating some parts of well determined behaviour allows you to control the component only by changing input data and testing the results.
  • 32. Two ways of Reacting. 1. Stateless functions Why? Simple. ./stateless/Header.jsx import { detectSomething } from '../../lib/detectors'; const Header = (props) => { const link = detectSomething(props.baseUrl) === 'meetJS' ? '/meetRegistration' : '/leave'; return ( <header> <h1>Register</h1> <a href={link} className='register-link'>Register now</a> </header> ); };
  • 33. Two ways of Reacting. 2. Stateful components Why? Extendable. ./stateful/Header.jsx import { detectSomething } from '../../lib/detectors'; class Header extends React.Component { render() { const link = detectSomething(this.props.baseUrl) === 'meetJS' ? '/meetRegistration' : '/leave'; return ( <header> <h1>Register</h1> <a href={link} className='register-link'>Register now</a> </header> ); } }
  • 34. THE FUTURE OF REACT We have started knowing react when he was 0.13.0 Now he is 0.14.7 - what changed?
  • 35. React is evolving. He is kind enough not to break our code. Every version introduces some changes, but they are well described, showing developers that things will change. This gave us some time, to remove more than 200 warnings from our code, before version changed. Now we have 0.
  • 36. React announced its stability. In a strange way. From the begining people were expecting the final version 1.0.0
  • 37. Surprise. We have now version 15.0.0.
  • 38. SO… why we react?Artur Szott @arturszott Simplicity (after some trials and errors) Testability (after learning finding good tools and setup) Performance (haven’t encountered bottlenecks as fast as with backbone)
  • 39. Bonus. Inspire yourself by reading following articles: Artur Szott @arturszott JSX looks like abomination, but it’s good for you. https://medium.com/javascript-scene/jsx-looks-like-an-abomination-1c1ec351a918 9 things every React.js beginner should know https://camjackson.net/post/9-things-every-reactjs-beginner-should-know Using React is a Business Decision, Not a Technology Choice https://blog.formidable.com/using-react-is-a-business-decision-not-a-technology-choice- 63c4641c5f7
  • 40. The end. You can work with me at HolidayCheck. github.com/holidaycheck/jobs Artur Szott @arturszott Photo: https://twitter.com/notbrent/status/696091475256352768 | Backgrounds: Unsplash.com