SlideShare a Scribd company logo
Styling 
Components 
with JavaScript 
@bensmithett
Warning 
» Not a tutorial for use in production! 
» I'm not even using any of this outside 
late night hacks 
But there are some interesting new ideas. 
Let's explore them & challenge CSS best 
practices!
Components are awesome! 
Nobody builds pages any more. 
Here's an example Profile component: 
components/ 
Profile/ 
index.hbs 
index.css 
index.js
HTML Template 
<div class="profile"> 
<img class="profile__avatar" src="{{avatarUrl}}.jpg" /> 
<strong>{{username}}</strong> 
</div> 
Style 
.profile { 
border: 1px solid #ddd; 
overflow: hidden; 
} 
.profile__avatar { 
float: left; 
margin-right: 10px; 
}
Behaviour 
var Profile = function (el) { 
el.addEventListener("click", function () { 
console.log("hai!"); 
}); 
this.el = el; 
this.tmpl = Handlebars.compile(someTemplateString); 
}; 
Profile.prototype.render = function (state) { 
this.el.innerHTML = this.tmpl(state); 
};
Styling components with JavaScript
React combines HTML structure & behaviour 
var React = require("react"); 
var Profile = React.createClass({ 
handleClick: function () { 
console.log("hai"); 
}, 
render: function () { 
return ( 
<div class="profile"> 
<img class="profile__avatar" src="{this.props.avatarUrl}.jpg" 
onClick={this.handleClick} /> 
<strong>{this.props.username}</strong> 
</div> 
); 
} 
}); 
module.exports = Profile;
Styling components with JavaScript
That's a big dirty lie 
The component's CSS is one of its 
concerns, but it's off in some random 
other file. 
components/ 
Profile/ 
index.css 
index.jsx
The only connection: a class name 
// JS 
render: function () { 
return ( 
<div class="profile"> 
// ... 
</div> 
) 
} 
/* CSS */ 
.profile 
border: 1px solid #ddd; 
overflow: hidden;
Most things 
» JS Dependencies are explicitly required 
» HTML structure is right there in the 
file 
» JS behaviour is right there in the file 
CSS 
» In another file, the classes might have 
the same name ¯_()_/¯ 
It's a crappy, vague connection.
CSS builds are a bit backwards 
//app.scss 
@import vendor/Normalize.css; 
@import base; 
@import components/Header; 
@import components/Profile; 
@import components/Footer; 
You need to know which bits of CSS your 
app requires. Lame.
What if our JS build automatically 
created a stylesheet based only on the 
components we use? 
// app.js 
var Profile = require(./components/Profile); 
var Header = require(./components/Header); 
var Footer = require(./components/Footer); 
// app.css 
// Somehow... 
// components/Profile/index.css 
// components/Header/index.css 
// components/Footer/index.css 
// ... end up here?
Styling components with JavaScript
http://webpack.github.io/
var React = require(react); 
require(./index.css); 
var Profile = React.createClass({ 
render: function () { 
return ( 
div class=profile / 
); 
} 
}); 
module.exports = Profile;
// app.js 
var Profile = require(./components/Profile); 
var Header = require(./components/Header); 
var Footer = require(./components/Footer); 
// app.css generated by webpack 
.profile { ... } 
.profile__avatar { ... } 
.header { ... } 
.footer { ... }
Hooray! 
CSS is just another dependency we can 
require() in our component
Hooray? 
components/ 
Profile/ 
index.css 
index.jsx 
» Still working across 2 files 
» Need to maintain class names across 2 
files 
... still a bit lame.
React can do inline styles 
// Profile/index.js 
var Profile = React.createClass({ 
styles: { 
border: 1px solid #ddd, 
overflow: hidden 
}, 
render: function () { 
return( 
div style={this.styles} / 
); 
} 
}); 
!-- DOM generated by React -- 
div style=border: 1px solid #ddd; overflow: hidden; 
/div
Nobody likes inline 
styles though
What we really want: 
» Declare styles in the component, like 
we do with inline styles 
» Build process that... 
» converts them to a CSS class 
» spits out a shiny, auto-generated 
app.css 
» component knows to use that class 
name
React-style does that! 
» https://github.com/SanderSpies/react-style 
» http://andreypopp.com/posts/2014-08-06- 
react-style.html 
(with a little help from webpack)
var React = require(react/addons); 
var ReactStyle = require(react-style); 
var Profile = React.createClass({ 
styles: ReactStyle(function () { 
return { 
backgroundColor: green, 
border: 1px solid #ddd 
}; 
}), 
render: function () { 
return( 
div styles={this.styles()} / 
); 
} 
}); 
module.exports = Profile;
!-- DOM generated by React -- 
div class=a 
... 
/div 
// app.css generated by React-style  Webpack 
.a { 
background-color: green; 
border: 1px solid #ddd; 
}
Demo 
Compiling with default compressed class 
names
Demo 
Formatting class names
Do you even need 
a CSS naming 
convention?
not really... 
» Styles are tightly coupled part of the 
component, not a separate thing 
» CSS class naming conventions are a 
project setting, not an inherent 
property of the component 
» Dev: BEM class names for easy 
debugging 
» Prod: Tiny compressed class names
I 3 Sass 
$red: #f00; 
$grid-columns: 12; 
$base-font-size: 16px; 
@function px-to-em($px, $base: $base-font-size) { 
@return ($px / $base) * 1em; 
} 
%placeholder { 
color: $red; 
} 
.thing { 
@extend %placeholder; 
padding: 10px; 
}
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, 
other-property: other-value 
}; 
JavaScript can do that!
JS already has lots of Real Programming 
Language Things TM 
» Variables 
» Functions 
» Arrays  Objects 
» Loops 
» Maths 
» String manipulation 
» Dependency management
Warning! 
Total pseudocode, nothing past this point 
actually works
Example: color variables 
var colors = require(./color_palette); 
var Profile = React.createClass({ 
styles: ReactStyle(function () { 
return { 
color: colors[hotPink], 
}; 
}), 
render: function () { 
return( 
div styles={this.styles()} / 
); 
} 
});
Example: Generate a grid 
var gridColumns = 12; 
var styles = {}; 
for (var i = 1; i = gridColumns; i++) { 
var width = (i / gridColumns) * 100; 
styles[span- + i] = ReactStyle(function () { 
return { 
float: left, 
width: width + % 
} 
}); 
} 
var GridColumn = React.createClass({ 
styles: styles, 
render: function () { 
var columns = span- + this.props.columns; 
return( 
div styles={this.styles[columns]()} / 
); 
} 
});
2015 Hipster Preprocessor 
JavaScript?!
The end :) 
@bensmithett 
https://github.com/bensmithett/react-style-example 
https://github.com/SanderSpies/react-style 
https://github.com/chenglou/rcss 
https://github.com/hedgerwang/react-styles 
https://github.com/elierotenberg/react-css

More Related Content

PDF
Styling Components with JavaScript: MelbCSS Edition
bensmithett
 
PDF
Handlebars and Require.js
Ivano Malavolta
 
PDF
Learn about Eclipse e4 from Lars Vogel at SF-JUG
Marakana Inc.
 
PDF
Efficient Rails Test-Driven Development - Week 6
Marakana Inc.
 
PDF
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
Marakana Inc.
 
PDF
Efficient Rails Test Driven Development (class 4) by Wolfram Arnold
Marakana Inc.
 
PDF
Dependency Management with RequireJS
Aaronius
 
PDF
ActiveDOM
Felix Geisendörfer
 
Styling Components with JavaScript: MelbCSS Edition
bensmithett
 
Handlebars and Require.js
Ivano Malavolta
 
Learn about Eclipse e4 from Lars Vogel at SF-JUG
Marakana Inc.
 
Efficient Rails Test-Driven Development - Week 6
Marakana Inc.
 
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
Marakana Inc.
 
Efficient Rails Test Driven Development (class 4) by Wolfram Arnold
Marakana Inc.
 
Dependency Management with RequireJS
Aaronius
 

What's hot (19)

PDF
RequireJS & Handlebars
Ivano Malavolta
 
PPTX
SharePoint and jQuery Essentials
Mark Rackley
 
PPTX
JavaScript and jQuery Basics
Kaloyan Kosev
 
PDF
Real World Web components
Jarrod Overson
 
PPTX
Cartegraph Live HTML, CSS, JavaScript and jQuery Training
Shane Church
 
PDF
Introduction to javascript templating using handlebars.js
Mindfire Solutions
 
PPTX
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
crokitta
 
PDF
Building Web Sites that Work Everywhere
Doris Chen
 
PPTX
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Ayes Chinmay
 
PPTX
J query
David Giard
 
PPTX
How I Learned to Stop Worrying and Love jQuery (Jan 2013)
David Giard
 
PDF
Short intro to JQuery and Modernizr
Jussi Pohjolainen
 
PPTX
JQuery
Jussi Pohjolainen
 
PDF
jQuery in the [Aol.] Enterprise
Dave Artz
 
PDF
DirectToWeb 2.0
WO Community
 
PPT
Managing JavaScript Dependencies With RequireJS
Den Odell
 
PPT
jQuery Tips Tricks Trivia
Cognizant
 
PPTX
JsViews - Next Generation jQuery Templates
BorisMoore
 
RequireJS & Handlebars
Ivano Malavolta
 
SharePoint and jQuery Essentials
Mark Rackley
 
JavaScript and jQuery Basics
Kaloyan Kosev
 
Real World Web components
Jarrod Overson
 
Cartegraph Live HTML, CSS, JavaScript and jQuery Training
Shane Church
 
Introduction to javascript templating using handlebars.js
Mindfire Solutions
 
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
crokitta
 
Building Web Sites that Work Everywhere
Doris Chen
 
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Ayes Chinmay
 
J query
David Giard
 
How I Learned to Stop Worrying and Love jQuery (Jan 2013)
David Giard
 
Short intro to JQuery and Modernizr
Jussi Pohjolainen
 
jQuery in the [Aol.] Enterprise
Dave Artz
 
DirectToWeb 2.0
WO Community
 
Managing JavaScript Dependencies With RequireJS
Den Odell
 
jQuery Tips Tricks Trivia
Cognizant
 
JsViews - Next Generation jQuery Templates
BorisMoore
 
Ad

Viewers also liked (6)

PDF
Modern networking for php developers - Dutch PHP conference 2015
SynchroM
 
PDF
UX, ethnography and possibilities: for Libraries, Museums and Archives
Ned Potter
 
PDF
Designing Teams for Emerging Challenges
Aaron Irizarry
 
PDF
Visual Design with Data
Seth Familian
 
PDF
3 Things Every Sales Team Needs to Be Thinking About in 2017
Drift
 
PDF
How to Become a Thought Leader in Your Niche
Leslie Samuel
 
Modern networking for php developers - Dutch PHP conference 2015
SynchroM
 
UX, ethnography and possibilities: for Libraries, Museums and Archives
Ned Potter
 
Designing Teams for Emerging Challenges
Aaron Irizarry
 
Visual Design with Data
Seth Familian
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
Drift
 
How to Become a Thought Leader in Your Niche
Leslie Samuel
 
Ad

Similar to Styling components with JavaScript (20)

PDF
Practical HTML5: Using It Today
Doris Chen
 
PPTX
Javascript first-class citizenery
toddbr
 
KEY
[Coscup 2012] JavascriptMVC
Alive Kuo
 
PDF
Guia de Sobrevivência JS no mundo Open Source
Leonardo Balter
 
PDF
Wt unit 2 ppts client side technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
PDF
Wt unit 2 ppts client sied technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
PPT
Web performance essentials - Goodies
Jerry Emmanuel
 
PDF
Having Fun with Play
Clinton Dreisbach
 
PDF
Web Development for UX Designers
Ashlimarie
 
PDF
Webpack
Sofian Hadiwijaya
 
PPSX
RequireJS
Tim Doherty
 
PDF
Jquery presentation
Mevin Mohan
 
KEY
Jarv.us Showcase — SenchaCon 2011
Chris Alfano
 
PPT
J query b_dotnet_ug_meet_12_may_2012
ghnash
 
PDF
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
tdc-globalcode
 
PDF
Django Rest Framework and React and Redux, Oh My!
Eric Palakovich Carr
 
PDF
Integrating React.js Into a PHP Application
Andrew Rota
 
PDF
Assetic (Zendcon)
Kris Wallsmith
 
KEY
Javascript unit testing, yes we can e big
Andy Peterson
 
PDF
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
Guy Royse
 
Practical HTML5: Using It Today
Doris Chen
 
Javascript first-class citizenery
toddbr
 
[Coscup 2012] JavascriptMVC
Alive Kuo
 
Guia de Sobrevivência JS no mundo Open Source
Leonardo Balter
 
Wt unit 2 ppts client side technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
Wt unit 2 ppts client sied technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
Web performance essentials - Goodies
Jerry Emmanuel
 
Having Fun with Play
Clinton Dreisbach
 
Web Development for UX Designers
Ashlimarie
 
RequireJS
Tim Doherty
 
Jquery presentation
Mevin Mohan
 
Jarv.us Showcase — SenchaCon 2011
Chris Alfano
 
J query b_dotnet_ug_meet_12_may_2012
ghnash
 
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
tdc-globalcode
 
Django Rest Framework and React and Redux, Oh My!
Eric Palakovich Carr
 
Integrating React.js Into a PHP Application
Andrew Rota
 
Assetic (Zendcon)
Kris Wallsmith
 
Javascript unit testing, yes we can e big
Andy Peterson
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
Guy Royse
 

Recently uploaded (20)

PDF
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
PPTX
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
PPT
SCOPE_~1- technology of green house and poyhouse
bala464780
 
PPTX
Tunnel Ventilation System in Kanpur Metro
220105053
 
PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
PDF
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
DOCX
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
PPTX
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
PDF
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
PDF
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
PDF
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
PDF
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
PPTX
Information Retrieval and Extraction - Module 7
premSankar19
 
PPT
Ppt for engineering students application on field effect
lakshmi.ec
 
PDF
Introduction to Data Science: data science process
ShivarkarSandip
 
PPTX
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
PDF
Zero Carbon Building Performance standard
BassemOsman1
 
PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PPTX
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
SCOPE_~1- technology of green house and poyhouse
bala464780
 
Tunnel Ventilation System in Kanpur Metro
220105053
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
Information Retrieval and Extraction - Module 7
premSankar19
 
Ppt for engineering students application on field effect
lakshmi.ec
 
Introduction to Data Science: data science process
ShivarkarSandip
 
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
Zero Carbon Building Performance standard
BassemOsman1
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 

Styling components with JavaScript

  • 1. Styling Components with JavaScript @bensmithett
  • 2. Warning » Not a tutorial for use in production! » I'm not even using any of this outside late night hacks But there are some interesting new ideas. Let's explore them & challenge CSS best practices!
  • 3. Components are awesome! Nobody builds pages any more. Here's an example Profile component: components/ Profile/ index.hbs index.css index.js
  • 4. HTML Template <div class="profile"> <img class="profile__avatar" src="{{avatarUrl}}.jpg" /> <strong>{{username}}</strong> </div> Style .profile { border: 1px solid #ddd; overflow: hidden; } .profile__avatar { float: left; margin-right: 10px; }
  • 5. Behaviour var Profile = function (el) { el.addEventListener("click", function () { console.log("hai!"); }); this.el = el; this.tmpl = Handlebars.compile(someTemplateString); }; Profile.prototype.render = function (state) { this.el.innerHTML = this.tmpl(state); };
  • 7. React combines HTML structure & behaviour var React = require("react"); var Profile = React.createClass({ handleClick: function () { console.log("hai"); }, render: function () { return ( <div class="profile"> <img class="profile__avatar" src="{this.props.avatarUrl}.jpg" onClick={this.handleClick} /> <strong>{this.props.username}</strong> </div> ); } }); module.exports = Profile;
  • 9. That's a big dirty lie The component's CSS is one of its concerns, but it's off in some random other file. components/ Profile/ index.css index.jsx
  • 10. The only connection: a class name // JS render: function () { return ( <div class="profile"> // ... </div> ) } /* CSS */ .profile border: 1px solid #ddd; overflow: hidden;
  • 11. Most things » JS Dependencies are explicitly required » HTML structure is right there in the file » JS behaviour is right there in the file CSS » In another file, the classes might have the same name ¯_()_/¯ It's a crappy, vague connection.
  • 12. CSS builds are a bit backwards //app.scss @import vendor/Normalize.css; @import base; @import components/Header; @import components/Profile; @import components/Footer; You need to know which bits of CSS your app requires. Lame.
  • 13. What if our JS build automatically created a stylesheet based only on the components we use? // app.js var Profile = require(./components/Profile); var Header = require(./components/Header); var Footer = require(./components/Footer); // app.css // Somehow... // components/Profile/index.css // components/Header/index.css // components/Footer/index.css // ... end up here?
  • 16. var React = require(react); require(./index.css); var Profile = React.createClass({ render: function () { return ( div class=profile / ); } }); module.exports = Profile;
  • 17. // app.js var Profile = require(./components/Profile); var Header = require(./components/Header); var Footer = require(./components/Footer); // app.css generated by webpack .profile { ... } .profile__avatar { ... } .header { ... } .footer { ... }
  • 18. Hooray! CSS is just another dependency we can require() in our component
  • 19. Hooray? components/ Profile/ index.css index.jsx » Still working across 2 files » Need to maintain class names across 2 files ... still a bit lame.
  • 20. React can do inline styles // Profile/index.js var Profile = React.createClass({ styles: { border: 1px solid #ddd, overflow: hidden }, render: function () { return( div style={this.styles} / ); } }); !-- DOM generated by React -- div style=border: 1px solid #ddd; overflow: hidden; /div
  • 21. Nobody likes inline styles though
  • 22. What we really want: » Declare styles in the component, like we do with inline styles » Build process that... » converts them to a CSS class » spits out a shiny, auto-generated app.css » component knows to use that class name
  • 23. React-style does that! » https://github.com/SanderSpies/react-style » http://andreypopp.com/posts/2014-08-06- react-style.html (with a little help from webpack)
  • 24. var React = require(react/addons); var ReactStyle = require(react-style); var Profile = React.createClass({ styles: ReactStyle(function () { return { backgroundColor: green, border: 1px solid #ddd }; }), render: function () { return( div styles={this.styles()} / ); } }); module.exports = Profile;
  • 25. !-- DOM generated by React -- div class=a ... /div // app.css generated by React-style Webpack .a { background-color: green; border: 1px solid #ddd; }
  • 26. Demo Compiling with default compressed class names
  • 28. Do you even need a CSS naming convention?
  • 29. not really... » Styles are tightly coupled part of the component, not a separate thing » CSS class naming conventions are a project setting, not an inherent property of the component » Dev: BEM class names for easy debugging » Prod: Tiny compressed class names
  • 30. I 3 Sass $red: #f00; $grid-columns: 12; $base-font-size: 16px; @function px-to-em($px, $base: $base-font-size) { @return ($px / $base) * 1em; } %placeholder { color: $red; } .thing { @extend %placeholder; padding: 10px; }
  • 31. What is a Preprocessor? A language that helps us generate blocks of key:value pairs. selector { property: value; other-property: other-value; }
  • 32. What is a Preprocessor? A language that helps us generate blocks of key:value pairs. selector = { property: value, other-property: other-value }; JavaScript can do that!
  • 33. JS already has lots of Real Programming Language Things TM » Variables » Functions » Arrays Objects » Loops » Maths » String manipulation » Dependency management
  • 34. Warning! Total pseudocode, nothing past this point actually works
  • 35. Example: color variables var colors = require(./color_palette); var Profile = React.createClass({ styles: ReactStyle(function () { return { color: colors[hotPink], }; }), render: function () { return( div styles={this.styles()} / ); } });
  • 36. Example: Generate a grid var gridColumns = 12; var styles = {}; for (var i = 1; i = gridColumns; i++) { var width = (i / gridColumns) * 100; styles[span- + i] = ReactStyle(function () { return { float: left, width: width + % } }); } var GridColumn = React.createClass({ styles: styles, render: function () { var columns = span- + this.props.columns; return( div styles={this.styles[columns]()} / ); } });
  • 38. The end :) @bensmithett https://github.com/bensmithett/react-style-example https://github.com/SanderSpies/react-style https://github.com/chenglou/rcss https://github.com/hedgerwang/react-styles https://github.com/elierotenberg/react-css