I have a simple modal:
renderModalForm() {
return (
<Modal
closeTimeoutMS={150}
show={this.state.isModalOpen}
onHide={this.isModalOpen.bind(this)}
>
<Modal.Body>
<div className="close-button-modal">
<i className="fa fa-times fa-2x pull-right" onClick={this.onButtonClick.bind(this)}></i>
<div className="clearfix"></div>
</div>
<div ref="test" className="testclassname">
</div>
</Modal.Body>
</Modal>
);
}
My sole objective is to inject a custom attribute (which unfortunately cannot start with data- or aria- since it's defined by third party) to the div
referenced by ref="test"
When I attempt to inject the custom attribute:
someButtonClicked() {
setTimeout(() => {
this.setState({
isModalOpen: true
})
}, 100);
var element = ReactDOM.findDOMNode(this.refs.test);
element.setAttribute('doku-div', 'form-payment');
}
Here element is always undefined, so setAttribute
failed; if I go inspect the element, ref="test"
does not exist at the <div>
! Can someone help me as to why this ref is missing inside modal?
Try moving your code to
ComponentDidMount
orComponentDidUpdate
method. Refs shouldn't be undefined there.You can also use a callback to store a reference to the DOM node:
And then use that reference instead of using ReactDOM: