xzk
xzk

Reputation: 877

Reactjs - OnClick modal popup on its own

I am learning Reactjs and faced with a small problem.

Inside a table cell, I created a button and onclick, it should popup a modal.

<td className="">
    <div className="radio">
    {(() => {
            return (item.ElectionOptions.split(",").map((item1, index1) =>
            <label key={index1} className="radio-inline">
                <input type="radio" id={index} value={item1}
                checked={item.Election===item1}
                onChange={this.handleOptionChange}
                />{item1}
            </label>
            ))
    })()}
    </div>
    <div>
        {(() => {
            if (roleUpdate) {
                return (<button fontSize="20px" data-toggle="modal" onClick={this.handleEditOptions(item)}>Edit Options</button>)
            }
        })()}
    </div>
</td>

The handleEditOption is created separately:

handleEditOptions = (item) => {
        var modal = (<VotingOptionModal resolutiondata = {item} />);
        ReactDOM.render(modal, document.getElementById('x-modal'));

    }

Problem is: when I reload the page, the popup modal appeared on its own (which should not happen), as if I already clicked on the button. Furthermore, I subsequently closed the modal, and then clicked on the button, the modal does not appear. I think something is wrong with the event handler. But not sure how I should fix it.

Please kindly help. Thank you.

Upvotes: 0

Views: 1417

Answers (3)

illiteratewriter
illiteratewriter

Reputation: 4323

When you write functionName(), the function gets called and the function runs. Whereas, if you write functionName alone, the value of the function gets passed, and it will be ran onClick. So you can either write

onClick={() => handleEditOptions(item)}

In this an anonymous function is passed to the onClick, and the function will be ran only on Click.

Upvotes: 0

Colin Ricardo
Colin Ricardo

Reputation: 17239

In this line:

return (<button fontSize="20px" data-toggle="modal" onClick={this.handleEditOptions(item)}>Edit Options</button>)

you're doing onClick={this.handleEditOptions(item)} which is running the function.

Instead, try onClick={() => this.handleEditOptions(item)}.

Upvotes: 1

3Dos
3Dos

Reputation: 3487

onClick={() => this.handleEditOptions(item)}

will fix this.

onClick expects a function as value. Writing onClick={this.handleEditOptions(item)} gives onClick the result of this.handleEditOptions(item) as a value.

So the workaround here is to wrap this method call into an anonymous function

Upvotes: 0

Related Questions