le.lop
le.lop

Reputation: 33

How to call an onClick Function when creating a span, In react

I am working in react and when a button is clicked, a li item gets created, in the list item I have a span with a glyphicon, i want to create an onClick event for the glyphicon, but it doesn't work.

Html

<ul id="list"></ul>

this is the method which creates the list item

var listItem = document.createElement("li");              
        listItem.innerHTML = this.tokenSeries;
        var span = document.createElement("span");
        span.innerHTML = "<span class='glyphicon glyphicon-remove' onClick={this.test}></span>" 
        listItem.appendChild(span);
        document.getElementById('list').appendChild(listItem);

this is my test method

@action.bound test() {
        alert("hello");
    }

Upvotes: 0

Views: 3072

Answers (3)

le.lop
le.lop

Reputation: 33

after setting the html set the onclick method to call the function you want

var listItem = document.createElement("li");              
            listItem.innerHTML = "text"
            var span = document.createElement("span");
            span.innerHTML = "<span class='glyphicon glyphicon-remove' ></span>" 
            span.onclick = this.test;
            listItem.appendChild(span);
            document.getElementById('list').appendChild(listItem);

Or you can create a function right there

 var listItem = document.createElement("li");              
                listItem.innerHTML = "text"
                var span = document.createElement("span");
                span.innerHTML = "<span class='glyphicon glyphicon-remove' ></span>" 
                span.onclick = function(){
                //write your function here
                };
                listItem.appendChild(span);
                document.getElementById('list').appendChild(listItem);

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281894

If you are using React you can do it the React Way instead of going by the VanillaJS method

constructor() {
     super();
     this.state = {
          list: []
     }
}

addListItem = () => {
     var list = [...this.state.list];
     var ele= <li>{this.tokenSeries}<span className='glyphicon glyphicon-remove' onClick={this.test}></span></li>
     list.push(ele)
     this.setState({list})
}

//render

<ul id="list">{this.state.list}</ul>

Upvotes: 1

Ariasa
Ariasa

Reputation: 1979

I Hope its good :)

var listItem = document.createElement("li");              
    listItem.innerHTML = this.tokenSeries;
    var span = document.createElement("span").on('click', (e) => {
     //place to call function trigger
     this.test(e);
    });
    span.innerHTML = "<span class='glyphicon glyphicon-remove'></span>" 
    listItem.appendChild(span);
    document.getElementById('list').appendChild(listItem);

Upvotes: 1

Related Questions