Reputation: 11991
During on click on each boxes I would like to get the tags
of the corresponding box. But while console log the print tags, it is displaying as undefined. I have tried both cases like e.currentTarget.tags
and e.target.tags
, but still not getting the correct result. Could someone please help ?
Demo link:
https://codesandbox.io/s/serene-elgamal-lyyih?file=/src/App.js:87-1914
const blogData = [
{
id: 1,
title: "Cypress tests",
description: "Add the E2E cypress UI tests",
createddate: "19 September 2020",
tags: "cypress"
},
{
id: 2,
title: "Jmeter tests",
description: "Performance test using Jmeter tool",
createddate: "15 August 2020",
tags: ["jmeter", "performance"]
},
{
id: 3,
title: "Basic Unix commands",
description: "Learn basic unix commands in git bash",
createddate: "10 July 2020",
tags: "unix"
},
{
id: 4,
title: "Postman",
description: "Api testing using postman",
createddate: "1 June 2020",
tags: ["postman", "api"]
}
];
export default function App() {
const [searchResults, setSearchResults] = useState([]);
const [showColor, setShowColor] = useState("");
const [findTag, setFindTag] = useState("");
useEffect(() => {
setSearchResults(blogData);
}, [blogData]);
const randomizedHex = (e) => {
setFindTag(e.currentTarget.tags);
console.log("Print tag:", findTag);
const randomColor = "#" + Math.floor(Math.random() * 16777215).toString(16);
setShowColor(randomColor);
};
return (
<div className="App">
<div className="wrap">
{searchResults.map((blog) => (
<article onClick={randomizedHex} className="equalBox">
<section>
<span key={blog.id}> {blog.id} </span>
</section>
<section>
<div key={blog.tags}>{blog.tags}</div>
</section>
</article>
))}
</div>
</div>
);
}
Upvotes: 0
Views: 67
Reputation: 44900
The code needs to pass the blog
object to the callback:
const randomizedHex = (blog) => {
setFindTag(blog.tags);
console.log("Print tag:", findTag);
const randomColor = "#" + Math.floor(Math.random() * 16777215).toString(16);
setShowColor(randomColor);
};
return (
<div className="App">
<div className="wrap">
{searchResults.map((blog) => (
<article onClick={() => { randomizedHex(blog); }} className="equalBox">
<section>
<span key={blog.id}> {blog.id} </span>
</section>
<section>
<div key={blog.tags}>{blog.tags}</div>
</section>
</article>
))}
</div>
</div>
);
Upvotes: 1