How To Combine Multiple Inline Style Objects In ReactJS

Hello Guys,

We’ll learn how to combine numerous inline style objects into a single style object in React in this article.

Instead of utilizing a CSS string, we may use a JavaScript Object with camelCase attributes to provide inline styles to the element in React.

Example:

App.js:

import React from 'react';

const box = {
    color: "green",
    fontSize: '23px'
}

function App(){
    return (
      <div style={box}>
         <h1>Hello react</h1>
      </div>
    )
}
export default App;

Combining multiple objects:

If you have many inline style objects, you can use the spread operator to merge them.

App.js:

import React from 'react';

const box = {
    color: "green",
    fontSize: '23px'
}

const shadow = {
    background: "orange",
    boxShadow: "1px 1px 1px 1px #cccd"
}

function App(){
    return (
      <div style={{...box, ...shadow}}>
         <h1>Hello react</h1>
      </div>
    )
}
export default App;

Using the spread operator, we combine the two objects (box, shadow) into a single style object in the preceding code.

Similarly, the Object.assign()function can be used.

import React from "react";

const box = {
  color: "green",
  fontSize: "23px"
};

const shadow = {
  background: "orange",
  boxShadow: "1px 1px 1px 1px #cccd"
};

function App() {
  return (
    <div style={Object.assign({}, box, shadow)}>
      <h1>Hello react</h1>
    </div>
  );
}
export default App;

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories