Question

Which is the preferred place to add an event listener in your code if you're using SPFx and React?

The .ts file or the .tsx file?

And which function, componentDidMount, getInitialState, render?

The reason for asking is that I've got a checkbox in my HTML and would like to add a click event to it. When clicked, I want to check all other checkboxes on the page.

The event listener is added when I run my code, but all my tries to collect all other checkboxes only results in the first two checkboxes being added to my array.

The same code works in the browser console, which is why I'm wondering if my event handler might be in the wrong place.

Any input would be appreciated, thanks.

Was it helpful?

Solution

You don't really add it inside a lifecycle function, you just add a reference to your handler function in the onClick property of your element. Which I guess technically is "inside" the render function.

Here's a little pseudo-code example (without all the TypeScript stuff from SPFx):

class MyComponent extends React.Component {
    componentDidMount = () => {
        // you could do stuff here if you need to,
        // but not hooking up an event handler
    }

    // this is your event handler.
    // it's just its own separate function
    // that's part of your component
    handleClick = () => {
        // check to see if your main checkbox is checked,
        // then get the other checkboxes and check them
    }

    render() {
        return (
            <div>
                <input type='checkbox' onClick={this.handleClick}></input>
            </div>
        )
    }
}

As far as reliably collecting all the other checkboxes, you could add a class to all of them that doesn't have any styling rules, but you could still use it to do

document.querySelectorAll('.yourCheckboxClass')

The real problem that I see, though is this: is the "checked" state of any of your checkboxes stored/controlled in component state? If so, modifying the DOM elements directly is going to get those elements out of sync with their components. You would have to figure out some way of calling a function on all the other components to set the checkbox state in order to "check" it. You could do it by passing around callback functions through props, or pub/sub might be a good solution there - have your master checkbox publish a "checked" message when it's checked, and have all the other checkboxes subscribing to that, and setting themselves as checked when they receive the message...

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top