David
David

Reputation: 569

react js binding click event

I'm new to reactjs, I have stuck in between please help me out here :

I have a class component in react js. And I have <ul></li></li></ul>, here I'm adding <li> from jquery after some DB query. Now how can I add onClick event to li ? bcz when I'm adding it from jquery i.e it's giving 'undefined function this.getValue' in react js.

Here is below example :

class getData extends React.Component {

    constructor(props) {
        super(props);
    }

    getValue(p1,p2,p3) {
        .... 
    }

    render() {

        var dropdown = <ul id="dropD"></ul>

        return (
            {dropdown}
        )
    }
} 

Now from Jquery, I'm get li with some DB query and appending it to ul as below

<li onClick=this.getValue('x','xx','xxx')>value 1</li>
<li onClick=this.getValue('x','xx','xxx')>value 2</li>
<li onClick=this.getValue('x','xx','xxx')> ... </li>

Here I'm getting all the dropdown properly, but when I click on dropdown (li) tag, I'm getting as 'undefined this.getValue function' because I'm adding it dynamically. If I hard code the li under ul, it is able to recognize the function and is working properly, only issue when I add li dynamically.

Please let me know if I add li tag dynamically then how can I call onClick function inside class component

Upvotes: 1

Views: 3999

Answers (1)

jennas
jennas

Reputation: 2454

Using jQuery to modify your react DOM tree is considered an anti-pattern and you should not do it. This is only going to cause you a world of pain when React attempts to compare against the virtual DOM. In fact, I'm surprised React is not warning you of this already.

What is the reason you do not want to add the new li children from within React itself?

Also, another thing is jumping out at me too, your component in this example is called getData. What is this component designed to do? It seems like a strange name to use.

If you are trying to populate a drop down I suggest you use componentDidMount to do your database call and update your view data on success.

example

class MySelectBox extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            items: ['Orange', 'Banana', 'Apple']
        };
    }

    componentDidMount() {
        window.$.ajax({
            url: "/api/getMyItem"
        }).done(function(result) {
            this.setState((state) => {
                state.items.push(result);
                return state;
            });
        });
    }

    handleClickEvent(e, value) {
        .... 
    }

    render() {
        return (
            <ul>
                {this.state.items.map((label) => {
                    return (
                        <li onClick={this.handleClickEvent.bind(this, label)}>
                            {label}
                        </li>
                    );
                })}
            </ul>
        );
    }
} 

Upvotes: 1

Related Questions