ReactJS
Read carefully the Refs and the DOM part of the React documentation.
React is working using virtual DOM.
export default function App() {
const removeBtns = ['x1', 'x2'];
const removeQuestion = () => {
console.log('test');
};
return (
<div className='container'>
{removeBtns.map((x) => (
<a key={x} href={'#!'} onClick={removeQuestion}>
{x}
</a>
))}
</div>
);
}
HTML
Try onClick="removeQuestion()" or onClick={removeQuestion()}
The value accepted by onclick in html is the javascript statement executed when clicked.
The value accepted by onclick in javascript is the callback function executed when clicked.
const removeBtn1 = '<a onClick={removeQuestion()}> x1 </a>';
const removeBtn2 = '<a onClick="removeQuestion()"> x2 </a>';
const removeQuestion = () => {
console.log('test')
};
window.document.body.insertAdjacentHTML('afterbegin', [removeBtn1, removeBtn2]);
Also you can try EventListener.
const removeBtn1 = '<a class="btn"> x1 </a>';
const removeBtn2 = '<a class="btn"> x2 </a>';
window.document.body.insertAdjacentHTML('afterbegin', [removeBtn1, removeBtn2]);
document.querySelectorAll('.btn').forEach(btn => {
btn.addEventListener('click', () => {
console.log('test');
});
});
insertAdjacentHTMLin a React app when you shouldn't be (React deals with DOM updates and doesn't understand when another process interferes). You should add your button to your JSX and show it conditionally based on some state that is triggered at some point.