React - Style Attribute

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).

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>;
}

Example

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>

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>

Documentation / Reference





Discover More
React - Styled Component

Styled component is a Css In Js solution. Utilising tagged template literals and the power of CSS, styled-components allows you to write actual CSS code to style your components. styled-components ...
React - Styling

Styling a component in React. Traditional CSS-file-based styling with the import of stylesheet (with SASS, PostCSS, ..) SSR does not like it very much. See No Pseudo Classes/Element No Media...



Share this page:
Follow us:
Task Runner