realist
realist

Reputation: 2375

Show MaterialUi snackbar by method

I want to show message in material.ui by only call method not ading component to parent component (like toastify.js). So, I wrote example like below. But I couldn't call showSnack() method. How can I achieve this?

Note: I don't want add component to demo js like < SnackbarHelper />. I only want show snackbar calling by function.

CODESANDBOX LINK

Demo.js

import React from "react";
import Button from "@material-ui/core/Button";
import SnackHelper from "./snackHelper";

export default function PositionedSnackbar() {
  function showMessage() {
    console.log("I want call snackHelper.showSnack");
    // snackHelper.showSnack();
  }

  return (
    <div>
      <Button variant="contained" onClick={() => showMessage()}>
        SHOW MESSAGE
      </Button>
    </div>
  );
}

snackbarHelper.js

import React from "react";
import Snackbar from "@material-ui/core/Snackbar";

export default function SnackHelper() {
  const [state, setState] = React.useState({
    open: false
  });

  const { vertical, horizontal, open } = state;

  const showSnack = (newState) => () => {
    setState({ open: true, ...newState });
  };

  const handleClose = () => {
    setState({ ...state, open: false });
  };

  return (
    <div>
      <Snackbar
        anchorOrigin={{ vertical, horizontal }}
        open={open}
        onClose={handleClose}
        message=""
        key={vertical + horizontal}
      />
    </div>
  );
}

Upvotes: 8

Views: 4239

Answers (1)

realist
realist

Reputation: 2375

I found solution in this article for same thing what I was looking. Only difference is, this is for confirmation dialog and written by typescript. But, it can be easily changed to toast message by javascript. https://dev.to/dmtrkovalenko/the-neatest-way-to-handle-alert-dialogs-in-react-1aoe

You can get working example code https://codesandbox.io/s/neat-dialogs-3h5ou?from-embed=&file=/src/ConfirmationService.tsx

Upvotes: 4

Related Questions