I want to color different elements based on their own ids. If their id is in a list of id's given by me, make it a color, if not, make it another color.
In the example below are 4 div's, each a different color. How can I color each div depending on his id without defining css rules for each of them?
const Main = () => {
return (
<React.Fragment>
<div id='1' style={{background: 'red'}}>1</div>
<div id='2' style={{background: 'blue'}}>2</div>
<div id='3' style={{background: 'green'}}>3</div>
<div id='4' style={{background: 'cyan'}}>4</div>
</React.Fragment>
)
}
https://jsfiddle.net/9debt3cL/19/
If the question is not very clear, let me know.
UPDATE: Context: I have an svg blueprint divided into multiple parts, each with a unique number. I have to fetch some data containing some parts of the blueprint numbers and depending on those numbers to fill the blueprint paths.
Not completely sure if it would work but you could always try, look into a switch case using javascript. Set the expression and have different cases depending on the value etc. Can be Id in this example and have a different outcome depending on the case.
I think Wanz has the right approach, you can create css classes with the desired attributes. Then add this class to the dom element if it corresponds to the switch case. Like so:
var element = document.getElementById("myDIV");
switch (expr) {
case 'id1':
element.classList.add("styleId1");
break;
case 'id2':
element.classList.add("styleId2");
case 'id3':
element.classList.add("styleId3");
break;
default:
console.log(`no matching id`);
}
You could so something like this:
const Main = () => {
const coloredIds = ['1', '4'];
const getBackgroundColor = (id) => {
return coloredIds.includes(id) ? 'cyan' : 'red';
}
return (
<React.Fragment>
<div id='1' style={{background: getBackgroundColor('1')}}>1</div>
<div id='2' style={{background: getBackgroundColor('2')}}>2</div>
<div id='3' style={{background: getBackgroundColor('3')}}>3</div>
<div id='4' style={{background: getBackgroundColor('4')}}>4</div>
</React.Fragment>
);
}
or if you have multiple colors
const getBackgroundColor = (id) => {
switch (id) {
case '1':
return 'red';
case '2':
return 'blue;
case '3':
return 'green';
case '4':
default:
return 'cyan';
}
}