I have a list, containing some jsx components like components:
components = [
<span className="c1 c2" onClick={() => console.log("test")}>...</span>,
<span className="c1 c2" onClick={() => console.log("test")}>...</span>,
<span className="c1 c2" onClick={() => console.log("test")}>...</span>,
]
BTW the components, is made with push
ing into array:
for(...) {
components.push(<span ...>...</span>)
}
and i use this list as below:
const MyList = () => {
return (
<p>{components}</p>
)
}
the problem is that, after rendering, items don’t have any onClick (or onclick
event handler) function.
although they have class
property, and the event
is set to function noop() {}
.
Browsers inspector shows them like:
// there is no 'onclick' function
<span class="c1 c2">...</span>
...
New problem:
Suppose that c2
class is like:
.c2{
color: blue;
}
.c2:hover {
cursor: pointer;
}
It changes color of text to blue, but it doesn’t show pointer
on hover(doesn’t do anything on hover), too.
I appreciate any help.
2
Answers
Event handlers like
onClick
only work when elements are created and rendered within React’s rendering process (as in the "render" in class components). If you create and store JSX elements in an array outside the component’s lifecycle (like in your example), React won’t properly attach event handlers to those elements.You should do this instead
The case above assumes that your components are rendering only
span
tags. If they were dynamic, say you want to render adiv
, abutton
and ap
tag, I would do this instead – create the array to have objects with theelementType
andprops
There is no problem creating an array of elements with
onClick
. When the elements are rendered, the click handlers will work properly. In the demo below, click each letter to see the corresponding handler respond –