React.js inline style best practices
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:
- Layout — how an element/component looks in relationship to others
- Appearance — the characteristics of an element/component
- Behavior and state — how an element/component looks in a given state
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:
// Typical component with state-classes
<li
className={classnames({ 'todo-list__item': true, 'is-complete': item.complete })} />
// Using inline-styles for state
<li className='todo-list__item'
style={(item.complete) ? styles.complete : {}} />
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:
// Supporting multiple-states with inline-styles
<li 'todo-list__item'
style={Object.assign({}, item.complete && styles.complete, item.due && styles.due )}>
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:
<li 'todo-list__item'
style={Object.assign({},
item.due && styles.due,
item.due && this.props.dueStyles)}>
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.
// This couples your component to the layout system
// It reduces the reusability of your component
<UserBadge
className="col-xs-12 col-sm-6 col-md-8"
firstName="Michael"
lastName="Chan" />
// This is much easier to maintain and change
<div class="col-xs-12 col-sm-6 col-md-8">
<UserBadge
firstName="Michael"
lastName="Chan" />
</div>
For layout support, I often try to design components to be 100%
width
and height
.
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:
var styles = {
root: {
display: "block"
},
item: {
color: "black"
complete: {
textDecoration: "line-through"
},
due: {
color: "red"
}
},
}
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:
React.createClass({
getStyles: function () {
return Object.assign(
{},
item.props.complete && styles.complete,
item.props.due && styles.due,
item.props.due && this.props.dueStyles
);
},
render: function () {
return <li style={this.getStyles()}>{this.props.item}</li>
}
});
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
best practice to style react components
The best way is to use Radium for pseudo elements or media queries
class Button extends React.Component {
render() {
return (
<button
style={{styles}}>
{this.props.children}
</button>
);
}
}
Button = Radium(Button);
const styles = {
backgroundColor: red,
':hover': {
backgroundColor: black
}
};
Inline-styles in ReactJS
Declare your inline style as an object:
<button style={{ background: 'yellow' }} onClick={this.handleClick}>
{this.state.isHelpOn ? 'HELP ON' : 'HELP OFF'}
</button>
Is there tag styling in react js inline style
const fontStyles = {
fontSize:"24px"
}
Add the styled object to your p tag.
<p style={fontStyles}> hello </p>
<p style={fontStyles}> world </p>
You can use Styled components. It's recommended in React and good best practices Check the Docs
https://styled-components.com/
Using Styled Components
const MyStyledParagraph = styled.p`
font-size : 24px
`
Best this if you export the MyStyledParagraph Component you can use anywhere in the project. Styled Component use CSS styled syntax. (fontSize is use as font-size, like in CSS)
<MyStyledParagraph>Hello</MyStyledParagraph>
<MyStyledParagraph>World</MyStyledParagraph>
How to add !important into React inline CSS style
Apparently it is not supported https://github.com/facebook/react/issues/1881#issuecomment-262257503
meanwhile you can use a hack doing:
<div ref={element => {
if (element) element.style.setProperty('border', '2px', 'important');
}}
/>
Correct way to handle conditional styling in React
If you prefer to use a class name, by all means use a class name.
className={completed ? 'text-strike' : null}
You may also find the classnames package helpful. With it, your code would look like this:
className={classNames({ 'text-strike': completed })}
There's no "correct" way to do conditional styling. Do whatever works best for you. For myself, I prefer to avoid inline styling and use classes in the manner just described.
POSTSCRIPT [06-AUG-2019]
Whilst it remains true that React is unopinionated about styling, these days I would recommend a CSS-in-JS solution; namely styled components or emotion. If you're new to React, stick to CSS classes or inline styles to begin with. But once you're comfortable with React I recommend adopting one of these libraries. I use them in every project.
Related Topics
Why Does Applying a Css-Filter on the Parent Break the Child Positioning
Change Navbar Color in Twitter Bootstrap
How to Remove Focus Border (Outline) Around Text/Input Boxes - Chrome
Reset/Remove CSS Styles For Element Only
Css Display: Inline VS Inline-Block
Border Gradient With Border Radius
Stretch and Scale a CSS Image in the Background - With CSS Only
Remove White Space Below Image
Transparent Arrow/Triangle Indented Over an Image
Black Transparent Overlay on Image Hover With Only Css
How and Where to Use ::Ng-Deep
:First-Child Not Working as Expected
Is Embedding Background Image Data into CSS as Base64 Good or Bad Practice
Change Button Border Color When the Button Is Being Clicked and After