Vivek kalanka
Vivek kalanka

Reputation: 102

dynamically created button onclick is not working in react js

I dynamically create a button element in my javascript function and then add an onclick event to that button. But after I press that button I get this error Uncaught ReferenceError: removeQuestionis not defined (removeQuestionis is my function name )

this is the button i created inside of my js function

const addQuestions = () => {
   const removeBtn = '<a color="primary" onClick={removeQuestion}> x</a>';
   window.document.body.insertAdjacentHTML('beforeend', removeBtn);
};

this function are called by onclick

const removeQuestion = () => {
        console.log('test')
    };

Upvotes: 0

Views: 1070

Answers (3)

Vivek kalanka
Vivek kalanka

Reputation: 102

this is issue with insertAdjacentHTML i used React.createElement and after rendered using ReactDOM.render

let input = React.createElement("input",{className:"questionTextInput",name:"textInputQuestion[]"},null);
   ReactDOM.render(input,questionPreview);

Upvotes: 0

vivek kalanka
vivek kalanka

Reputation: 21

this is issue with insertAdjacentHTML you can use ReactDOM.render

 let input = React.createElement("input",{className:"questionTextInput",name:"textInputQuestion[]"},null);
   ReactDOM.render(input,questionPreview);

Upvotes: 1

Ian
Ian

Reputation: 1179

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');
  });
});

Upvotes: 1

Related Questions