The task is: implement React component for toasts - hiding by itself, showing from outside. Most of React guides describe how to access DOM from React component. Almost nothing about how to access React component from DOM. My code for React component is:
import React from "react";
export default class Alert extends React.Component {
constructor(props) {
super(props);
this.type = null;
this.message = null;
this.state = { show: false };
this.alertCallbackRef = alert => { window.toast = alert; };
}
show = (type, message) => {
this.type = type;
this.message = message;
this.setState({ show: true });
}
hide = () => {
this.setState({ show: false });
}
render() {
return (
<>
<div ref={this.alertCallbackRef}> // here ref
{
this.state.show ? (
// here visible part
) : null
}
</div>
</>
);
}
}
Then check <Alert/> tag on HTML page:
- window.toast contains DOM Node <div></div>.
- window.toast.any_function (show / hide / etc) - is not a function.
What's wrong?
div, not to the component.window.toast = thisshould work in the constructor