Probably a dumb question so apologies in advance. I'm working on a budgeting tool and one of the things that I want to do is to change the background colour of a component based on the remaining budget the user has. My initial thought was to use props to pass the data into the component, and then use that data to decide which CSS classname to give the div which would then decide the background colour.
`
const bucketStyle = ""
const remBudget = props.remainingBudget;
if (remBudget >= 50) {
bucketStyle = "savings-board-bucket-wrapper-green";
} else {
bucketStyle = "savings-board-bucket-wrapper-red";
}
function SavingsBoardBucket(props) {
return (
<div className='savings-board-bucket-wrapper'>
<div className={ bucketStyle }>
<p className='savings-board-bucket-label'>{ props.remainingBudget }</p>
</div>
</div>
)
}`
However, that doesn't work because props are passed down but can't be passed up. The only other thing that I could think of would be to use a ternary operator and pass in the background colour as a prop (aka props.backgroundColour = red/green) and use that in a ternary operator to flip the CSS, but that's not great for readability and I'd ideally like to have more than just two colour options. Any advice? Thanks for any help, I really appreciate it.
I don't know the specifics of your code as it's not all clear the question, but in case you would like to categorize the divs based on the budget values while the budget values are available for the div, it would work something like the following
React
function App({}) {
const data =[
{title: "Low Budget", budget: 25},
{title: "Medium Low Budget", budget: 45},
{title: "Medium Budget", budget: 70},
{title: "High Budget", budget: 120},
]
return (
<div>
{data.map(
(item)=> <BudgetComponent title={item.title} budgetValue={item.budget}/>)
}
</div>
);
}
function BudgetComponent({budgetValue, title}){
const budgetToClassesMap= (budget) => {
switch(true){
case (budget < 30):
return "low-budget";
case (budget >= 30 && budget < 60):
return "medium-low-budget";
case (budget >= 60 && budget < 100):
return "medium-budget";
case (budget >= 100):
return "high-budget";
default:
return "budget-unknown";
}
}
return (
<div className={budgetToClassesMap(budgetValue)}>
{title}
<div>
Other Stuff
</div>
</div>)
}
ReactDOM.render(<App />, document.querySelector("#app"))
CSS
div{
padding: .5em;
}
.low-budget{
background: red;
}
.medium-low-budget{
background: yellow;
}
.medium-budget{
background: lightgreen ;
}
.high-budget{
background: green;
}