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:
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.
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>
);
}