I'm trying to change the color of svg elements by comparing the id's of the elements with an array. I'm getting the correct comparison results by looping the id's of all the available elements and comparing them with the array data. However, I'm not able to dynamically color the compared element.
This is what I have tried so far: CodeSandBox
import React from "react";
import "./App.css";
import NewTestColor from "./NewTestColor";
const App = () => {
const data = [
{
id: "D",
hmc: "",
lmc: "low"
},
{
id: "B",
hmc: "high",
lmc: ""
},
{
id: "A",
hmc: "high",
lmc: ""
},
{
id: "C",
hmc: "",
lmc: "low"
}
];
const addEventListener =
("mouseup",
(e) => {
// Let's pick a random color between #000000 and #FFFFFF
const rnd = Math.round(Math.random() * 0xffffff);
// Let's format the color to fit CSS requirements
const fill = "#" + rnd.toString(16).padStart(6, "0");
// Let's apply our color in the
// element we actually clicked on
e.target.style.fill = fill;
const id = e.target.getAttribute("id");
console.log(id);
console.log(fill);
// console.log(data);
});
// const Ndata = data.filter(task => task.hmc === "high")
// .map(filteredData => {filteredData.id}, {filteredData.hmc}, {filteredData.color} )
const FilteredData = data.filter((e) => e.hmc.includes("high"));
const OnlyIp = FilteredData.map((e) => `${e.id} ${e.hmc}`);
// console.log(OnlyIp)
console.log(FilteredData);
return (
<div>
<NewTestColor onClick={addEventListener} items={FilteredData} />
</div>
);
};
export default App;
The issue is if you define onClick as a prop on a component you defined it does not work. You need to add it to an actual element like svg.
Change the NewTestColor to pass to onClick function to outer svg
const NewTestColor = ({ onClick }) => (
<svg viewBox="0 0 210 297" height={500} width={500} onClick={onClick}>
...
...
...
</svg>
);
And the addEventListener function in App.js should look like below.
const addEventListener = (e) => {
// Let's pick a random color between #000000 and #FFFFFF
const rnd = Math.round(Math.random() * 0xffffff);
// Let's format the color to fit CSS requirements
const fill = "#" + rnd.toString(16).padStart(6, "0");
// Let's apply our color in the
// element we actually clicked on
e.target.style.fill = fill;
const id = e.target.getAttribute("id");
console.log(id);
console.log(fill);
// console.log(data);
};