Languages

React - how to merge multiple inline style objects?

3 points
Asked by:
Niac
208

Does anyone know how to merge two multiple inline style objects by assigning them both to one div element?

This is what I want to do:

import React from 'react';

const myStyle1 = {
  color: 'blue',
  background: 'lightblue',
  justifyContent: 'center',
  display: 'flex',
};

const myStyle2 = {
  fontSize: '20px',
  border: '3px solid lightgreen',
  borderRadius: '10px',
};

const App = () => {
  return <div style={{ myStyle1, myStyle2 }}> my div </div>;
};

export default App;
1 answer
3 points
Answered by:
Niac
208

The solution I found says that I should use the spread operator (...) while assigning the objects like this:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const myStyle1 = {
  color: 'blue',
  background: 'lightblue',
  justifyContent: 'center',
  display: 'flex',
};

const myStyle2 = {
  fontSize: '20px',
  border: '3px solid lightgreen',
  borderRadius: '10px',
};

const App = () => {
  return <div style={{ ...myStyle1, ...myStyle2 }}> my div </div>;
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

or copy myStyle1 to the myStyle2 object and assign just one style to the div:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const myStyle1 = {
  color: 'blue',
  background: 'lightblue',
  justifyContent: 'center',
  display: 'flex',
};

const myStyle2 = {
  ...myStyle1,
  fontSize: '20px',
  border: '3px solid lightgreen',
  borderRadius: '10px',
};

const App = () => {
  return <div style={myStyle2}> my div</div>;
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join