<html>
<head>
<meta charset="UTF-8" />
<script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.14.7/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
function App() {
const data = [
{ id: 1, text: "Item 1" },
{ id: 2, text: "Item 2" },
{ id: 3, text: "Item 3" },
];
const getStyle = (itemId) => {
if (itemId === 1) {
return { backgroundColor: "red", color: "white" };
} else if (itemId === 2) {
return { backgroundColor: "blue", color: "white" };
} else {
return { backgroundColor: "brown", color: "yellow" };
}
};
return (
<div className="container">
<h3>React change style of element in map</h3>
{data.map((item) => (
<div key={item.id} style={getStyle(item.id)}>
<p>{item.text}</p>
</div>
))}
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
<style>
#app {
margin: 0 auto;
width: 500px;
text-align: center;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.12),
0 2px 4px 0 rgba(0, 0, 0, 0.24);
padding: 20px;
}
/* Styling for the heading */
.container h1 {
font-size: 24px;
text-align: center;
margin-bottom: 20px;
}
/* Styling for the list */
.container ul {
list-style: none;
padding: 0;
margin: 0;
}
/* Styling for the list items */
.container li {
font-size: 18px;
margin-bottom: 8px;
}
/* Styling for odd-indexed list items (alternating background) */
.container li:nth-child(odd) {
background-color: #f9f9f9;
padding: 8px;
border-radius: 4px;
}
</style>
</body>
</html>