Reputation: 332
I'm beginner in ReactJS. I add HTML code in a div and this HTML code is for buttons, it's works, but the onClick attribute is always undefined. I tried two things but it doesn't work.
First try :
const createListPlaylist = (res) => {
if (res === undefined)
return;
var list = "";
for (let i = 0; i < res.data.items.length; i++)
list += `<Button onClick=${createPlaylistWidget(res.data.items[i].id)}>${res.data.items[i].name}</Button><br>`;
document.getElementById("PlayListViewer").innerHTML += list;
}
Second try :
const createListPlaylist = (res) => {
if (res === undefined)
return;
var list = "";
var listArray = [];
for (let i = 0; i < res.data.items.length; i++) {
listArray.push(createPlaylistWidget(res.data.items[i].id));
list += `<button onClick=${displayPlaylitSelected(listArray[i])}>${res.data.items[i].name}</button><br>`;
}
document.getElementById("PlayListViewer").innerHTML += list;
}
Result :
createListPlaylist
is called after an axios request and the res
parameter is the response of the request and yes res.data.items[i].id
is correct I can print in in the console with no problem. So, ask your help because I don't no why my onClick
attribute is undefined and I don't find the answer.
Thank you in advance for the answers.
Upvotes: 0
Views: 808
Reputation: 14365
You cannot make a string of JSX and expect it to behave as a component or use JSX syntax. JSX is just a cleaner/easier way of writing JavaScript function calls (specifically React.createElement()
.
Unfortunately there is no simple fix to the code you provided it will require you to re-approach the problem thinking in React, but I can point out the problem areas.
document.getElementById().innerHTML
is almost always an anti-pattern.onClick
.Upvotes: 0
Reputation: 1560
It's onClick
and not onclick
. Amend that change and it will work.
Pretty much all the props in react should be written in camelCase. Incase you want the element to appear in dom then you can write it in lowercase.
Also note, there is an exception for aria-*
attributes and data-*
data attributes to this case.
Upvotes: 0
Reputation: 4344
You need to pass functions to events inside {} in React;
...
.... onClick={()=>${.....}}
see below for more information;
https://reactjs.org/docs/handling-events.html
Upvotes: 1