React Styles
How to use styles in React?
The style
attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes.
Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes in JavaScript (e.g. node.style.backgroundImage
).
How to conditionally apply class attributes?
You shouldn't use curly braces inside quotes because it is going to be evaluated as a string.
Instead you need to move curly braces outside (don't forget to include spaces between class names):
Template strings will also work:
How to use React label element?
If you try to render a <label>
element bound to a text input using the standard for
attribute, then it produces HTML missing that attribute and prints a warning to the console.
Since for
is a reserved keyword in JavaScript, use htmlFor
instead.
How to combine multiple inline style objects?
You can use spread operator in regular React:
If you're using React Native then you can use the array notation:
How do you apply vendor prefixes to inline styles in React?
React does not apply vendor prefixes automatically. You need to add vendor prefixes manually.
What are the popular packages for animation?
React Transition Group and React Motion are popular animation packages in React ecosystem.
What is the benefit of styles modules?
It is recommended to avoid hard coding style values in components. Any values that are likely to be used across different UI components should be extracted into their own modules.
For example, these styles could be extracted into a separate component:
And then imported individually in other components: