Reputation: 611
I'm currently trying to use the React style attribute to style React components dynamically. The first styling condition using the attribute is working properly, however on the second condition I'm getting this error: "Parsing error: Unexpected token, expected "}"" Here is my code:
<input
className="inputFieldComponent"
id={field.name}
type={field.type}
value={value}
disabled={(parentState.primaryVinRetrieved && field.name === 'makePrimary')
|| (parentState.primaryVinRetrieved && field.name === 'modelPrimary')
|| (parentState.secondaryVinRetrieved && field.name === 'makeSecondary')
|| (parentState.secondaryVinRetrieved && field.name === 'modelSecondary')}
placeholder={field.placeholder}
onChange={handleInputChange}
style={
field.currency && {
paddingLeft: '10px',
}
field.name === 'makePrimary' && {
color: 'grey',
}
}
/>
Basically I'm trying to chain additional conditionals into the style attribute. Not sure if this is the proper syntax for this. If there is a better way to accomplish this pls advise. Thanks.
Upvotes: 1
Views: 6351
Reputation: 1077
You can simply add new properties in styles object as styles is nothing, it just an object, so you can add new properties like this:
var data = {}; data["property"] = 4;
So, in your code, you can use your style operator as:
style = { styles }
where, styles is:
let styles = {};
if(field.name === 'makePrimary') styles["color"] = 'grey';
if(field.currency) styles["paddingLeft"] = '10px';
Another approach is to use spread operator.
You can use styled component as well as it help in passing parameter dynamically in css file. For more reference to this, follow the link given below: https://styled-components.com/
Upvotes: 1
Reputation: 35563
You can conditionally spread objects.
<input
className="inputFieldComponent"
id={field.name}
type={field.type}
value={value}
disabled={
(parentState.primaryVinRetrieved && field.name === 'makePrimary') ||
(parentState.primaryVinRetrieved && field.name === 'modelPrimary') ||
(parentState.secondaryVinRetrieved && field.name === 'makeSecondary') ||
(parentState.secondaryVinRetrieved && field.name === 'modelSecondary')
}
placeholder={field.placeholder}
onChange={handleInputChange}
style={{
...(field.currency
? {
paddingLeft: '10px',
}
: {}),
...(field.name === 'makePrimary'
? {
color: 'grey',
}
: {}),
}}
/>;
Upvotes: 1
Reputation: 3996
You can use the object spread operator - this works well with style objects composition:
style={{
...field.currency ? {
paddingLeft: '10px',
} : {},
...field.name === 'makePrimary' ? {
color: 'grey',
background: 'blue'
} : {}
}}
Upvotes: 5