SlideShare uma empresa Scribd logo
1 de 57
Baixar para ler offline
Styling 
Components 
with JavaScript 
@bensmithett
I already gave this talk at MelbJS 
Sorry if you're sitting through it again!
Warning: 
This talk is about writing CSS...
IN
JAVASCRIPT
Explore some new ideas and 
challenge best practices
CSS is not lacking Best Practices™ 
Sass • Less • Stylus • Myth • Autoprefixer 
OOCSS • BEM • SMACSS • SUIT • AMCSS 
No IDs • No inline styles • Use meaningful class 
names • Mobile first • Repetition is OK • 
Repetition is the devil • Avoid complex selectors 
• Use @extends • Don't use @extends • Don't 
write CSS in JavaScript
COMPONENTS!
The Profile component: 
views/ 
profile.html 
stylesheets/ 
profile.css 
javascripts/ 
profile.js
structure 
<div class="profile"> 
<img class="profile__avatar" src="{{user.avatar}}"> 
<strong>{{user.username}}</strong> 
</div>
style 
.profile { 
border: 1px solid #ddd; 
overflow: hidden; 
} 
.profile__avatar { 
float: left; 
margin-right: 10px; 
}
behaviour 
$(".profile").on("click", function(){ 
alert("hi"); 
});
Best practice: 
Separate HTML, CSS & JS
Why? 
Why is separating HTML, CSS & JS a best 
practice?
When we were building pages 
CSS classes loosely coupled to HTML 
.important { 
color: red; 
font-weight: bold; 
} 
JS behaviour loosely coupled to HTML 
$(".foo").fancyParallaxSlider()
Now... 
BEM Blocks, SMACSS Modules, SUIT 
Components 
Tightly couple styles to a very particular HTML 
structure 
Backbone Views, Angular Directives, Ember & 
React Components 
Tightly couple JS behaviour to a very particular 
HTML structure
views/ 
profile.html 
stylesheets/ 
profile.css 
javascripts/ 
profile.js
components/ 
profile/ 
profile.html 
profile.css 
profile.js
Component: 
A tightly coupled little bundle of HTML, 
CSS & JS
React is a library for building components
A React component 
• Describes the HTML structure given a 
particular application state 
• Reacts to user events (click, dragenter etc) 
that originate within the component
<div class="profile"> 
<img class="profile__avatar" src="{{user.avatar}}"> 
<strong>{{user.username}}</strong> 
</div>
$(".profile").on("click", function(){ 
alert("hi"); 
});
var Profile = React.createClass({ 
render: function () { 
return( 
<div className="profile" onClick={this.handleClick}> 
<img className="profile__avatar" 
src={this.props.avatarUrl} /> 
<strong>{this.props.username}</strong> 
</div> 
); 
}, 
handleClick: function () { 
alert("hi"); 
} 
});
components/ 
profile/ 
profile.html 
profile.css 
profile.js
components/ 
profile/ 
profile.jsx 
profile.css
The only real connection: a class name 
// JS 
render: function () { 
return ( 
<div className="profile"> 
// ... 
</div> 
) 
} 
/* CSS */ 
.profile 
border: 1px solid #ddd 
It's a crappy, vague connection.
Also, our CSS builds are a bit backwards 
/* app.scss */ 
@import vendor/Normalize.css; 
@import base; 
@import components/header; 
@import components/profile; 
@import components/footer;
Can't we do better?
What if our build process automatically 
built a stylesheet based only on the JS 
components we actually use?
Webpack 
// ComponentA.js 
require("./componentA.css"); 
// ComponentB.js 
require("./componentB.css"); 
// Javascript build generates app.css: 
// .component-a { ... } 
// .component-b { ... }
components/ 
profile/ 
profile.jsx 
profile.css
React can do inline styles 
var profileStyles = { 
border: "1px solid #ddd", 
overflow: "hidden" 
}; 
var Profile = React.createClass({ 
render: function () { 
return <div style={profileStyles} />; 
} 
}); 
<!-- DOM generated by React --> 
<div style="border: 1px solid #ddd; overflow: hidden"><div>
NOBODY LIKES 
INLINE STYLES
What we really want: 
• Declare styles in the component file, using 
JavaScript, like we do with inline styles 
• Build process that: 
• converts those styles to a CSS class 
• bundles up all generated CSS classes into a 
shiny CSS file 
• JS component magically knows which class 
name to use for a given element
react-style + webpack 
• github.com/SanderSpies/react-style 
• andreypopp.com/posts/2014-08-06-react-style. 
html 
• webpack.github.io
var Profile = React.createClass({ 
styles: ReactStyle({ 
backgroundColor: "green", 
border: "1px solid #ddd" 
}), 
render: function () { 
return <div styles={this.styles()} /> 
} 
})
/* app.css generated by react-style & webpack */ 
.a { 
background-color: green; 
border: 1px solid #ddd; 
} 
<!-- DOM generated by React --> 
<div class="a"> 
... 
</div>
Best practice: 
Use meaningful class 
names & a naming 
convention like BEM or 
SUIT
Why? 
We need a sensible class name that we can 
follow across seperate HTML, CSS & JS files 
Nope. All that stuff is in one file now.
var Profile = React.createClass({ 
styles: ReactStyle({ 
backgroundColor: "green", 
border: "1px solid #ddd" 
}), 
render: function () { 
return <div styles={this.styles()} /> 
} 
})
Why? 
We want to be able to inspect an element in the 
browser dev tools & see which component it 
belongs to. 
Yeah, this one is valid. 
But we can still automate it!
Automatically generate a BEM class name 
className = path.basename(fileName).split('.')[0].toLowerCase() + 
'__' + 
styleName; 
or a SUIT class name 
className = path.basename(fileName).split('.')[0] + 
'-' + 
styleName.charAt(0).toUpperCase() + 
styleName.slice(1);
CSS class naming conventions are a project 
setting, not an inherent property of the 
component. 
• Dev: BEM class names for easy debugging 
• Prod: Tiny minified class names
I <3 Sass
What is a preprocessor? 
A language that helps us generate blocks of 
key: value pairs. 
selector { 
property: value; 
other-property: other-value; 
}
What is a preprocessor? 
A language that helps us generate blocks of 
key: value pairs. 
selector = { 
property: "value", 
otherProperty: "other-value" 
}; 
OMG JavaScript can do that!
JS already has lots of Real Programming 
Things™ 
• Variables 
• Functions 
• Arrays & Objects 
• Loops 
• Maths 
• String manipulation 
• Dependency management
Things we can do in JS 
instead of a preprocessor 
Warning: everything beyond here is totally pseudocode that may or 
may not actually work
Example: Color variables 
var colors = require("color_palette"); 
var styles = { 
color: colors["primary"] 
} 
var Profile = React.createClass({ 
render: function () { 
return <div style={styles} />; 
} 
});
Example: Generate a grid 
var gridColumns = 12; 
var gridDefinitions = {}; 
for (var i = 1; i <= gridColumns; i++) { 
gridDefinitions["span-" + i] = { 
float: left, 
width: ((i / gridColumns) * 100) + "%" 
} 
} 
var GridColumn = React.createClass({ 
render: function () { 
var columns = "span-" + this.props.columnCount; 
return <div style={gridDefinitions[columns]} /> 
} 
})
2015 HIPSTER PREPROCESSOR 
JAVASCRIPT?!
Give it 5 minutes
the end :) 
@bensmithett

Mais conteúdo relacionado

Mais procurados

Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery BasicsKaloyan Kosev
 
Cartegraph Live HTML, CSS, JavaScript and jQuery Training
Cartegraph Live HTML, CSS, JavaScript and jQuery TrainingCartegraph Live HTML, CSS, JavaScript and jQuery Training
Cartegraph Live HTML, CSS, JavaScript and jQuery TrainingShane Church
 
Introduction to javascript templating using handlebars.js
Introduction to javascript templating using handlebars.jsIntroduction to javascript templating using handlebars.js
Introduction to javascript templating using handlebars.jsMindfire Solutions
 
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Ayes Chinmay
 
Building Web Sites that Work Everywhere
Building Web Sites that Work EverywhereBuilding Web Sites that Work Everywhere
Building Web Sites that Work EverywhereDoris Chen
 
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012crokitta
 
How I Learned to Stop Worrying and Love jQuery (Jan 2013)
How I Learned to Stop Worrying and Love jQuery (Jan 2013)How I Learned to Stop Worrying and Love jQuery (Jan 2013)
How I Learned to Stop Worrying and Love jQuery (Jan 2013)David Giard
 
jQuery Tips Tricks Trivia
jQuery Tips Tricks TriviajQuery Tips Tricks Trivia
jQuery Tips Tricks TriviaCognizant
 
Short intro to JQuery and Modernizr
Short intro to JQuery and ModernizrShort intro to JQuery and Modernizr
Short intro to JQuery and ModernizrJussi Pohjolainen
 
Getting Started with jQuery
Getting Started with jQueryGetting Started with jQuery
Getting Started with jQueryAkshay Mathur
 
Whirlwind Tour of SVG (plus RaphaelJS)
Whirlwind Tour of SVG (plus RaphaelJS)Whirlwind Tour of SVG (plus RaphaelJS)
Whirlwind Tour of SVG (plus RaphaelJS)Marc Grabanski
 
About Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JSAbout Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JSNaga Harish M
 
Web performance essentials - Goodies
Web performance essentials - GoodiesWeb performance essentials - Goodies
Web performance essentials - GoodiesJerry Emmanuel
 

Mais procurados (19)

RequireJS & Handlebars
RequireJS & HandlebarsRequireJS & Handlebars
RequireJS & Handlebars
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery Basics
 
Cartegraph Live HTML, CSS, JavaScript and jQuery Training
Cartegraph Live HTML, CSS, JavaScript and jQuery TrainingCartegraph Live HTML, CSS, JavaScript and jQuery Training
Cartegraph Live HTML, CSS, JavaScript and jQuery Training
 
Introduction to javascript templating using handlebars.js
Introduction to javascript templating using handlebars.jsIntroduction to javascript templating using handlebars.js
Introduction to javascript templating using handlebars.js
 
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
 
Building Web Sites that Work Everywhere
Building Web Sites that Work EverywhereBuilding Web Sites that Work Everywhere
Building Web Sites that Work Everywhere
 
J query
J queryJ query
J query
 
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
 
DirectToWeb 2.0
DirectToWeb 2.0DirectToWeb 2.0
DirectToWeb 2.0
 
How I Learned to Stop Worrying and Love jQuery (Jan 2013)
How I Learned to Stop Worrying and Love jQuery (Jan 2013)How I Learned to Stop Worrying and Love jQuery (Jan 2013)
How I Learned to Stop Worrying and Love jQuery (Jan 2013)
 
jQuery Tips Tricks Trivia
jQuery Tips Tricks TriviajQuery Tips Tricks Trivia
jQuery Tips Tricks Trivia
 
Short intro to JQuery and Modernizr
Short intro to JQuery and ModernizrShort intro to JQuery and Modernizr
Short intro to JQuery and Modernizr
 
JQuery
JQueryJQuery
JQuery
 
JQuery
JQueryJQuery
JQuery
 
Getting Started with jQuery
Getting Started with jQueryGetting Started with jQuery
Getting Started with jQuery
 
Whirlwind Tour of SVG (plus RaphaelJS)
Whirlwind Tour of SVG (plus RaphaelJS)Whirlwind Tour of SVG (plus RaphaelJS)
Whirlwind Tour of SVG (plus RaphaelJS)
 
About Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JSAbout Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JS
 
Web performance essentials - Goodies
Web performance essentials - GoodiesWeb performance essentials - Goodies
Web performance essentials - Goodies
 

Destaque

React for .net developers
React for .net developersReact for .net developers
React for .net developersmacsdickinson
 
Modern networking for php developers - Dutch PHP conference 2015
Modern networking for php developers - Dutch PHP conference 2015Modern networking for php developers - Dutch PHP conference 2015
Modern networking for php developers - Dutch PHP conference 2015SynchroM
 
React.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOMReact.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOMJimit Shah
 
Webpack & React Performance in 16+ Steps
Webpack & React Performance in 16+ StepsWebpack & React Performance in 16+ Steps
Webpack & React Performance in 16+ StepsGrgur Grisogono
 
React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesomeAndrew Hull
 
Incremental DOM and Recent Trend of Frontend Development
Incremental DOM and Recent Trend of Frontend DevelopmentIncremental DOM and Recent Trend of Frontend Development
Incremental DOM and Recent Trend of Frontend DevelopmentAkihiro Ikezoe
 
UX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesUX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesNed Potter
 
Designing Teams for Emerging Challenges
Designing Teams for Emerging ChallengesDesigning Teams for Emerging Challenges
Designing Teams for Emerging ChallengesAaron Irizarry
 
Visual Design with Data
Visual Design with DataVisual Design with Data
Visual Design with DataSeth Familian
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017Drift
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheLeslie Samuel
 

Destaque (11)

React for .net developers
React for .net developersReact for .net developers
React for .net developers
 
Modern networking for php developers - Dutch PHP conference 2015
Modern networking for php developers - Dutch PHP conference 2015Modern networking for php developers - Dutch PHP conference 2015
Modern networking for php developers - Dutch PHP conference 2015
 
React.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOMReact.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOM
 
Webpack & React Performance in 16+ Steps
Webpack & React Performance in 16+ StepsWebpack & React Performance in 16+ Steps
Webpack & React Performance in 16+ Steps
 
React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesome
 
Incremental DOM and Recent Trend of Frontend Development
Incremental DOM and Recent Trend of Frontend DevelopmentIncremental DOM and Recent Trend of Frontend Development
Incremental DOM and Recent Trend of Frontend Development
 
UX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesUX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and Archives
 
Designing Teams for Emerging Challenges
Designing Teams for Emerging ChallengesDesigning Teams for Emerging Challenges
Designing Teams for Emerging Challenges
 
Visual Design with Data
Visual Design with DataVisual Design with Data
Visual Design with Data
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 

Semelhante a Styling Components with JavaScript: MelbCSS Edition

CSS Methodology
CSS MethodologyCSS Methodology
CSS MethodologyZohar Arad
 
Inline style best practices in reactjs
Inline style best practices in reactjsInline style best practices in reactjs
Inline style best practices in reactjsBOSC Tech Labs
 
CSS101 - Concept Fundamentals for non UI Developers
CSS101 - Concept Fundamentals for non UI DevelopersCSS101 - Concept Fundamentals for non UI Developers
CSS101 - Concept Fundamentals for non UI DevelopersDarren Gideon
 
Girl Develop It Cincinnati: Intro to HTML/CSS Class 4
Girl Develop It Cincinnati: Intro to HTML/CSS Class 4Girl Develop It Cincinnati: Intro to HTML/CSS Class 4
Girl Develop It Cincinnati: Intro to HTML/CSS Class 4Erin M. Kidwell
 
2010 07-18.wa.rails tdd-6
2010 07-18.wa.rails tdd-62010 07-18.wa.rails tdd-6
2010 07-18.wa.rails tdd-6Marakana Inc.
 
TIBCO General Interface - CSS Guide
TIBCO General Interface - CSS GuideTIBCO General Interface - CSS Guide
TIBCO General Interface - CSS GuideRohan Chandane
 
Sass Essentials at Mobile Camp LA
Sass Essentials at Mobile Camp LASass Essentials at Mobile Camp LA
Sass Essentials at Mobile Camp LAJake Johnson
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Eric Palakovich Carr
 
J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012ghnash
 
JavaScript Modules in Practice
JavaScript Modules in PracticeJavaScript Modules in Practice
JavaScript Modules in PracticeMaghdebura
 
Front end workflow Presentation at Coffee@DBG by Praveen Vijayan
Front end workflow Presentation at Coffee@DBG by Praveen VijayanFront end workflow Presentation at Coffee@DBG by Praveen Vijayan
Front end workflow Presentation at Coffee@DBG by Praveen VijayanDeepu S Nath
 
Ajax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesAjax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesDoris Chen
 
Object-Oriented CSS 從 OOCSS, SMACSS, BEM 到 AMCSS
Object-Oriented CSS 從 OOCSS, SMACSS, BEM 到 AMCSSObject-Oriented CSS 從 OOCSS, SMACSS, BEM 到 AMCSS
Object-Oriented CSS 從 OOCSS, SMACSS, BEM 到 AMCSSLi-Wei Lu
 
Html / CSS Presentation
Html / CSS PresentationHtml / CSS Presentation
Html / CSS PresentationShawn Calvert
 
Implementing CSS support for React Native
Implementing CSS support for React NativeImplementing CSS support for React Native
Implementing CSS support for React NativeKristerKari
 

Semelhante a Styling Components with JavaScript: MelbCSS Edition (20)

CSS Methodology
CSS MethodologyCSS Methodology
CSS Methodology
 
Inline style best practices in reactjs
Inline style best practices in reactjsInline style best practices in reactjs
Inline style best practices in reactjs
 
CSS101 - Concept Fundamentals for non UI Developers
CSS101 - Concept Fundamentals for non UI DevelopersCSS101 - Concept Fundamentals for non UI Developers
CSS101 - Concept Fundamentals for non UI Developers
 
Girl Develop It Cincinnati: Intro to HTML/CSS Class 4
Girl Develop It Cincinnati: Intro to HTML/CSS Class 4Girl Develop It Cincinnati: Intro to HTML/CSS Class 4
Girl Develop It Cincinnati: Intro to HTML/CSS Class 4
 
2010 07-18.wa.rails tdd-6
2010 07-18.wa.rails tdd-62010 07-18.wa.rails tdd-6
2010 07-18.wa.rails tdd-6
 
TIBCO General Interface - CSS Guide
TIBCO General Interface - CSS GuideTIBCO General Interface - CSS Guide
TIBCO General Interface - CSS Guide
 
Sass Essentials at Mobile Camp LA
Sass Essentials at Mobile Camp LASass Essentials at Mobile Camp LA
Sass Essentials at Mobile Camp LA
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
J query
J queryJ query
J query
 
RequireJS
RequireJSRequireJS
RequireJS
 
An Introduction to CSS
An Introduction to CSSAn Introduction to CSS
An Introduction to CSS
 
J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012
 
Pfnp slides
Pfnp slidesPfnp slides
Pfnp slides
 
JavaScript Modules in Practice
JavaScript Modules in PracticeJavaScript Modules in Practice
JavaScript Modules in Practice
 
Front end workflow Presentation at Coffee@DBG by Praveen Vijayan
Front end workflow Presentation at Coffee@DBG by Praveen VijayanFront end workflow Presentation at Coffee@DBG by Praveen Vijayan
Front end workflow Presentation at Coffee@DBG by Praveen Vijayan
 
Ajax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesAjax Performance Tuning and Best Practices
Ajax Performance Tuning and Best Practices
 
Object-Oriented CSS 從 OOCSS, SMACSS, BEM 到 AMCSS
Object-Oriented CSS 從 OOCSS, SMACSS, BEM 到 AMCSSObject-Oriented CSS 從 OOCSS, SMACSS, BEM 到 AMCSS
Object-Oriented CSS 從 OOCSS, SMACSS, BEM 到 AMCSS
 
Html / CSS Presentation
Html / CSS PresentationHtml / CSS Presentation
Html / CSS Presentation
 
The Cascade is Dead
The Cascade is DeadThe Cascade is Dead
The Cascade is Dead
 
Implementing CSS support for React Native
Implementing CSS support for React NativeImplementing CSS support for React Native
Implementing CSS support for React Native
 

Último

MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 

Último (20)

MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 

Styling Components with JavaScript: MelbCSS Edition

  • 1. Styling Components with JavaScript @bensmithett
  • 2. I already gave this talk at MelbJS Sorry if you're sitting through it again!
  • 3. Warning: This talk is about writing CSS...
  • 4. IN
  • 6.
  • 7.
  • 8. Explore some new ideas and challenge best practices
  • 9. CSS is not lacking Best Practices™ Sass • Less • Stylus • Myth • Autoprefixer OOCSS • BEM • SMACSS • SUIT • AMCSS No IDs • No inline styles • Use meaningful class names • Mobile first • Repetition is OK • Repetition is the devil • Avoid complex selectors • Use @extends • Don't use @extends • Don't write CSS in JavaScript
  • 11. The Profile component: views/ profile.html stylesheets/ profile.css javascripts/ profile.js
  • 12. structure <div class="profile"> <img class="profile__avatar" src="{{user.avatar}}"> <strong>{{user.username}}</strong> </div>
  • 13. style .profile { border: 1px solid #ddd; overflow: hidden; } .profile__avatar { float: left; margin-right: 10px; }
  • 15. Best practice: Separate HTML, CSS & JS
  • 16. Why? Why is separating HTML, CSS & JS a best practice?
  • 17. When we were building pages CSS classes loosely coupled to HTML .important { color: red; font-weight: bold; } JS behaviour loosely coupled to HTML $(".foo").fancyParallaxSlider()
  • 18. Now... BEM Blocks, SMACSS Modules, SUIT Components Tightly couple styles to a very particular HTML structure Backbone Views, Angular Directives, Ember & React Components Tightly couple JS behaviour to a very particular HTML structure
  • 19. views/ profile.html stylesheets/ profile.css javascripts/ profile.js
  • 20. components/ profile/ profile.html profile.css profile.js
  • 21. Component: A tightly coupled little bundle of HTML, CSS & JS
  • 22.
  • 23. React is a library for building components
  • 24. A React component • Describes the HTML structure given a particular application state • Reacts to user events (click, dragenter etc) that originate within the component
  • 25. <div class="profile"> <img class="profile__avatar" src="{{user.avatar}}"> <strong>{{user.username}}</strong> </div>
  • 27. var Profile = React.createClass({ render: function () { return( <div className="profile" onClick={this.handleClick}> <img className="profile__avatar" src={this.props.avatarUrl} /> <strong>{this.props.username}</strong> </div> ); }, handleClick: function () { alert("hi"); } });
  • 28. components/ profile/ profile.html profile.css profile.js
  • 30. The only real connection: a class name // JS render: function () { return ( <div className="profile"> // ... </div> ) } /* CSS */ .profile border: 1px solid #ddd It's a crappy, vague connection.
  • 31. Also, our CSS builds are a bit backwards /* app.scss */ @import vendor/Normalize.css; @import base; @import components/header; @import components/profile; @import components/footer;
  • 32. Can't we do better?
  • 33. What if our build process automatically built a stylesheet based only on the JS components we actually use?
  • 34. Webpack // ComponentA.js require("./componentA.css"); // ComponentB.js require("./componentB.css"); // Javascript build generates app.css: // .component-a { ... } // .component-b { ... }
  • 36. React can do inline styles var profileStyles = { border: "1px solid #ddd", overflow: "hidden" }; var Profile = React.createClass({ render: function () { return <div style={profileStyles} />; } }); <!-- DOM generated by React --> <div style="border: 1px solid #ddd; overflow: hidden"><div>
  • 38. What we really want: • Declare styles in the component file, using JavaScript, like we do with inline styles • Build process that: • converts those styles to a CSS class • bundles up all generated CSS classes into a shiny CSS file • JS component magically knows which class name to use for a given element
  • 39. react-style + webpack • github.com/SanderSpies/react-style • andreypopp.com/posts/2014-08-06-react-style. html • webpack.github.io
  • 40. var Profile = React.createClass({ styles: ReactStyle({ backgroundColor: "green", border: "1px solid #ddd" }), render: function () { return <div styles={this.styles()} /> } })
  • 41. /* app.css generated by react-style & webpack */ .a { background-color: green; border: 1px solid #ddd; } <!-- DOM generated by React --> <div class="a"> ... </div>
  • 42. Best practice: Use meaningful class names & a naming convention like BEM or SUIT
  • 43. Why? We need a sensible class name that we can follow across seperate HTML, CSS & JS files Nope. All that stuff is in one file now.
  • 44. var Profile = React.createClass({ styles: ReactStyle({ backgroundColor: "green", border: "1px solid #ddd" }), render: function () { return <div styles={this.styles()} /> } })
  • 45. Why? We want to be able to inspect an element in the browser dev tools & see which component it belongs to. Yeah, this one is valid. But we can still automate it!
  • 46. Automatically generate a BEM class name className = path.basename(fileName).split('.')[0].toLowerCase() + '__' + styleName; or a SUIT class name className = path.basename(fileName).split('.')[0] + '-' + styleName.charAt(0).toUpperCase() + styleName.slice(1);
  • 47. CSS class naming conventions are a project setting, not an inherent property of the component. • Dev: BEM class names for easy debugging • Prod: Tiny minified class names
  • 49. What is a preprocessor? A language that helps us generate blocks of key: value pairs. selector { property: value; other-property: other-value; }
  • 50. What is a preprocessor? A language that helps us generate blocks of key: value pairs. selector = { property: "value", otherProperty: "other-value" }; OMG JavaScript can do that!
  • 51. JS already has lots of Real Programming Things™ • Variables • Functions • Arrays & Objects • Loops • Maths • String manipulation • Dependency management
  • 52. Things we can do in JS instead of a preprocessor Warning: everything beyond here is totally pseudocode that may or may not actually work
  • 53. Example: Color variables var colors = require("color_palette"); var styles = { color: colors["primary"] } var Profile = React.createClass({ render: function () { return <div style={styles} />; } });
  • 54. Example: Generate a grid var gridColumns = 12; var gridDefinitions = {}; for (var i = 1; i <= gridColumns; i++) { gridDefinitions["span-" + i] = { float: left, width: ((i / gridColumns) * 100) + "%" } } var GridColumn = React.createClass({ render: function () { var columns = "span-" + this.props.columnCount; return <div style={gridDefinitions[columns]} /> } })
  • 56. Give it 5 minutes
  • 57. the end :) @bensmithett