by Sai gowtham

How to combine multiple inline style objects in React

In this tutorial, we will learn about how to combine multiple inline style objects into a single style object in React.

In React, we can add a inline styles to the element using JavaScript Object with camelCase properties instead of a CSS string.

Example:

App.js
import React from 'react';

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

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

Combining multiple objects

If you have a multiple inline style objects, you can combine them by using a spread operator.

App.js
import React from 'react';

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

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

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

In the above code, we are combining the two objects ( box, shadow) into a single style object using the spread operator.

Similarly, you can also use the Object.assign() method.

import React from "react";

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

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

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

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course