React - Style Attribute

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React

1 - About

The style attribute in React element.

It accepts a JavaScript object with camelCased properties rather than a CSS string.

Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes from JS (e.g. node.style.backgroundImage).

Advertising

3 - Vendor Prefix

CSS - (Browser) Vendor (Property) Prefix

Styles are not autoprefixed.

Vendor prefixes other than ms should begin with a capital letter. This is why WebkitTransition has an uppercase “W”.

Example:

const divStyle = {
  WebkitTransition: 'all', // note the capital 'W' here
  msTransition: 'all' // 'ms' is the only lowercase vendor prefix
};
 
function ComponentWithTransition() {
  return <div style={divStyle}>This should work cross-browser</div>;
}

4 - Example

4.1 - Offline

The style attribute are in a variable object.

const divStyle = {
  color: 'white',
  backgroundColor: 'DarkTurquoise',
  padding: '1rem',
  display: 'inline-block',
  borderRadius: '4rem' 
};
 
function HelloWorldComponent() {
  return <div style={divStyle}>Hello World with Offline Style!</div>;
}
 
ReactDOM.render(
  <HelloWorldComponent/>,
  document.getElementById('root')
);
<div id="root">
<!-- called the "root" DOM node because everything inside it will be managed by React DOM -->
</div>

4.2 - Inline

The style attributes could also be given inline

function HelloWorldComponent() {
  return <div style={{
                    color: 'white',
                    backgroundColor: 'DarkTurquoise',
                    padding: '1rem',
                   display: 'inline-block',
                   borderRadius: '4rem' 
            }}>Hello World with Inline Style!</div>;
}
 
ReactDOM.render(
  <HelloWorldComponent/>,
  document.getElementById('root')
);
<div id="root">
<!-- called the "root" DOM node because everything inside it will be managed by React DOM -->
</div>

Advertising

5 - Documentation / Reference

web/javascript/react/style_attribute.txt · Last modified: 2019/02/16 17:40 by gerardnico