'Change color of individual items of array in React
I have fetched and displayed a list of json data: What it currently looks like in the browser.
I want to be able to change the background color of these buttons based on the value of the property in my json file, 'era'. If composer.era === 'Renaissance', setColor('red'). If composer.era === 'Baroque', setColor('blue'), etc...
Here is some of my json for reference:
{
"name": "Giulio Caccini",
"img": "/composerImgs/Caccini.jpeg",
"era": "Baroque",
"id": 23
},
{
"name": "Giovanni Gabrieli",
"img": "/composerImgs/Gabrieli.jpeg",
"era": "Renaissance",
"id": 24
},
Here is the fetch request from that json and how I'm currently handling it:
import {useState, useEffect} from 'react'
import { Login } from './Login'
import { Timeline } from './Timeline'
import { Results } from './Results'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import { Link } from "react-router-dom"
import './App.css'
import { styled } from '@mui/material/styles'
const ComposerButton = styled('button')({
width: '12rem',
height: '12rem',
position: 'relative',
right: '1rem',
border: 'none',
borderRadius: '25px'
})
const App = () => {
const [name, setName] = useState('');
const [composers, setComposers] = useState([]);
const [color, setColor] = useState('#27856a')
useEffect(() => {
const fetchComposers = async () => {
const response = await fetch('composers.json');
const data = await response.json();
const listofComposers = data.composers.map((composer) => {
return (
<Link to='/results'>
<ComposerButton style={{backgroundColor: color}} onClick={() => setName(composer.name)} key={composer.id}>
<ComposerName>{composer.name}</ComposerName>
{/* <ComposerImg src={composer.img}/> */}
</ComposerButton>
</Link>
)
})
setComposers(listofComposers);
}
fetchComposers();
}, []);
return (
<Router>
<Routes>
<Route path='/' element={<Login code={code} />} />
<Route path='/timeline' element={<Timeline composers={composers} />} />
<Route path='/results' element={<Results name={name} code={code} />} />
</Routes>
</Router>
);
}
export default App;
How can I change color depending on composer.era's value?
I've already tried:
const listofComposers = data.composers.map((composer) => {
if (composer.era === 'Renaissance'){
setColor('red')
}
if (composer.era === 'Baroque'){
setColor('blue')
}
etc...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
