0

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?

2
  • The ref is pointing to the div, not to the component. window.toast = this should work in the constructor Commented Feb 22, 2023 at 9:06
  • @Konrad: great! I'm so silly - ref don't return class instance, just some DOM nodes Commented Feb 22, 2023 at 9:44

1 Answer 1

1
  1. Cancel all about refs in code
  2. Just assign window.toast = this in constructor. Thanks to @Konrad
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.