Search code examples
javascripthtmlreactjsdombootstrap-4

ReactJS can not disable a dynamically created button


Using ReactJS I create a form dynamically using custom JSON data.

render() {      
    return (
        <div>       
            <ShowForm src={this.state.data} />
        </div>
    );
}

With componentDidUpdate I would like to disable all submit buttons. While the label of the buttons is changed successfully, I constantly fail to disable the button.

componentDidUpdate() {
    var submitButtons = document.querySelectorAll('button[type=submit]');
    submitButtons.forEach(btn => {
        btn.innerText = 'PREVIEW';
        btn.disabled = true;
    });
}

The chrome inspector returns the following HTML code for the buttons. Also, the form objects are using Bootstrap for the CSS styling.

<button lang="en" class="btn btn-warning btn-md" type="submit" name="data[Draft]" ref="button">PREVIEW</button>

What prevents JS to apply the disable action?


Solution

  • Web components is the preferred solutions

    https://reactjs.org/docs/web-components.html

    Alternatively, you can manipulate the JSON data before they are rendered from react-dom.

    Another solution I found is simply set pointer-events: none; style.

    componentDidUpdate() {
        var submitButtons = document.querySelectorAll('button[type=submit]');
        submitButtons.forEach(btn => {
            btn.setAttribute('style', 'pointer-events: none;');
        });
    }