Reputation: 1420
I have a select component and I need to add some extra padding to the options, based on a prop being passed. his is because in some situations, I have an icon absolutely positioned inside the select component and so want spacing on the left in such scenarios
render()
const { classes, icon, selectWithIcon } = this.props;
return(
<Select
value={this.state.value}
onChange={this.handleChange}
input={<FilledInput
name={this.props.label}
id={this.props.id} />}
>
{this.props.options && this.props.options.map(option => (
<MenuItem value={option.value} >
{<ListItemText className={classes.listItemText} primary={<Typography style={{ color: option.color, {selectWithIcon? marginLeft: '10px' : ''}}}>{option.text}</Typography>}/>}
</MenuItem>
))}
</Select>
)
how can I add a condition to style the primary inside MenuItem? The above code gives me an error
Upvotes: 1
Views: 41
Reputation: 80986
Here's the correct syntax (you need to put the condition in the value for marginLeft
rather than around the key in your style object):
<Typography
style={{
color: option.color,
marginLeft: selectWithIcon ? "10px" : ""
}}
>
{option.text}
</Typography>
Here's a full working example:
import React from "react";
import ReactDOM from "react-dom";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import ListItemText from "@material-ui/core/ListItemText";
import Typography from "@material-ui/core/Typography";
const MySelect = ({ selectWithIcon, options }) => {
return (
<Select value="1">
{options.map(option => (
<MenuItem value={option.value}>
{
<ListItemText
primary={
<Typography
style={{
color: option.color,
marginLeft: selectWithIcon ? "10px" : ""
}}
>
{option.text}
</Typography>
}
/>
}
</MenuItem>
))}
</Select>
);
};
function App() {
const options = [
{ text: "Item 1", value: 1, color: "blue" },
{ text: "Item 2", value: 2, color: "purple" }
];
return (
<div className="App">
<MySelect options={options} selectWithIcon={true} />
<br />
<MySelect options={options} selectWithIcon={false} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Upvotes: 1