Limpuls
Limpuls

Reputation: 876

How to apply multiple inline styles to a component as props?

I tried so many different things but nothing is working. It either breaks the application or only one style gets applied but not both at the same time. I have a parent component that passes some styles to a child and then the child itself has some local styles as well.

Parent component:

<CardSettings headline="Media accounts" size={{ flex: 1 }}></CardSettings>

Child component CardSettings.jsx:

const CardSettings = (props) => {
    return (
        <div style={({ background: '#fff' }, props.size)}>
            <h2 style={styles.headline}>{props.headline}</h2>
            {props.children}
        </div>
    )
}

What do I do wrong here? In this case flex: 1 gets applied but not background: #fff

Upvotes: 0

Views: 244

Answers (1)

Carl Edwards
Carl Edwards

Reputation: 14464

Considering your size prop is an object you could use spread syntax to merge in those styles with the ones already inside that div:

<div style={{ background: '#fff', ...props.size }}>
  <h2 style={styles.headline}>{props.headline}</h2>
  {props.children}
</div>

Pre-ES6 Solution:

Alternatively you could try Object.assign as so:

<div style={Object.assign({{}, background: '#fff', props.size)}>
  <h2 style={styles.headline}>{props.headline}</h2>
  {props.children}
</div>

Upvotes: 1

Related Questions