I'm aware that you can specify styles within React classes, like this:
const MyDiv = React.createClass({
render: function() {
const style = {
color: 'white',
fontSize: 200
};
return <div style={style}> Have a good and productive day! </div>;
}
});
Should I be aiming to do all styling this way, and have no styles at all specified in my CSS file?
Or should I avoid inline styles completely?
It seems odd and messy to do a little bit of both - two places would need to be checked when tweaking styling.
There aren't a lot of "Best Practices" yet. Those of us that are using inline-styles, for React components, are still very much experimenting.
There are a number of approaches that vary wildly: React inline-style lib comparison chart
All or nothing?
What we refer to as "style" actually includes quite a few concepts:
Start with state-styles
React is already managing the state of your components, this makes styles of state and behavior a natural fit for colocation with your component logic.
Instead of building components to render with conditional state-classes, consider adding state-styles directly:
Note that we're using a class to style appearance but no longer using any
.is-
prefixed class for state and behavior.We can use
Object.assign
(ES6) or_.extend
(underscore/lodash) to add support for multiple states:Customization and reusability
Now that we're using
Object.assign
it becomes very simple to make our component reusable with different styles. If we want to override the default styles, we can do so at the call-site with props, like so:<TodoItem dueStyle={ fontWeight: "bold" } />
. Implemented like this:Layout
Personally, I don't see compelling reason to inline layout styles. There are a number of great CSS layout systems out there. I'd just use one.
That said, don't add layout styles directly to your component. Wrap your components with layout components. Here's an example.
For layout support, I often try to design components to be
100%
width
andheight
.Appearance
This is the most contentious area of the "inline-style" debate. Ultimately, it's up to the component your designing and the comfort of your team with JavaScript.
One thing is certain, you'll need the assistance of a library. Browser-states (
:hover
,:focus
), and media-queries are painful in raw React.I like Radium because the syntax for those hard parts is designed to model that of SASS.
Code organization
Often you'll see a style object outside of the module. For a todo-list component, it might look something like this:
getter functions
Adding a bunch of style logic to your template can get a little messy (as seen above). I like to create getter functions to compute styles:
Further watching
I discussed all of these in more detail at React Europe earlier this year: Inline Styles and when it's best to 'just use CSS'.
I'm happy to help as you make new discoveries along the way :) Hit me up -> @chantastic