user924069
user924069

Reputation:

How to bind functional React component to class events

I'm trying to wrap my head around functional components and binding.

If I have a functional React component that looks like this:

const Dashboard = props => {
    const _dashboard = new _Dashboard()

    return (
        <div>
            <div className="title">Dashboard</div>
            <button>Log</button>
        </div>
    )
}

And a class that looks like this:

class _Dashboard {
    constructor() { }

    log() {
        console.log('Dashboard Log Clicked!')
    }
}

What is the proper way to bind the button click?

This is what I tried and doesn't work

const Dashboard = props => {
    const _dashboard = new _Dashboard()

    return (
        <div>
            <div className="title">Dashboard</div>
            <button onClick={ _dashboard.log }>Log</button>
        </div>
    )
}

but I feel like I'm missing something in the general way it works.

Edit: I removed the parenthesis from the log() call. Neither way is writing anything to the console.

Upvotes: 1

Views: 175

Answers (3)

Sanda
Sanda

Reputation: 1497

you are calling the function aka _dashboard.log() instead of _dashboard.log ;

Upvotes: 1

Patrick Klitzke
Patrick Klitzke

Reputation: 1559

you have to write something like:

 <button onClick={_dashboard.log}>Log</button>

or

 <button onClick={() => _dashboard.log()}>Log</button>

otherwise your code will be executed immediatly and not bound.

Upvotes: 0

Alejo Fernandez
Alejo Fernandez

Reputation: 21

You just need to remove the parenthesis otherwise you are actually invoking the function and binding onClick to the result of that function. Without parenthesis you pass a reference to the function.

<button onClick={_dashboard.log}>Log</button>

Upvotes: 0

Related Questions