I am fetching the list of categories from an api, I want to output the categoryId(id) associated with that category on click of that category. The json output of the api has id and name. This is the code I am using:
const fetchData = () => {
const categoryApi = "//apilink";
const getCategory = axios.get(categoryApi);
axios.all([getCategory, getStore]).then(
axios.spread((...allData) => {
const allCategory = allData[0].data.brand_categories;
setCategory(allCategory);
})
)
}
useEffect(() => {
fetchData()
}, [])
Printing the categories this way
<div className="sidebar">
<p style={{ fontSize: "20px", fontWeight: 600, marginTop: "0" }}>categories</p>
{
category.map((item) => (
<div>
{item.name}
</div>
))
}
</div>
enter code here
CodePudding user response:
As you mentioned you want to add onClick event to show the id on alert, if I got you right, it's simple if you got the id
inside the item
object (from category
array).
You can add the onClick attribute in the <div>
element, like so:
category.map((item) => (
<div onClick={() => alert(item.id)>
{item.name}
</div>
))`
You can either call for a function that will trigger onClick and will execute the code there if you want to alert or whatever you need else.
Hope you got the point, let me know if you need extra explanation.