Home > Mobile >  How to clear state on Dialog close React?
How to clear state on Dialog close React?

Time:09-28

I am using https://react-spectrum.adobe.com/react-spectrum/Dialog.html and whenever I close the dialog and reopen it the value I type does not default back to the initial state. How can I render Dialog on close to reset all states within the dialog?

import {
  ActionButton,
  Button,
  ButtonGroup,
  Content,
  Dialog,
  DialogTrigger,
  Divider,
  Header,
  Heading,
  Text,
  TextField,
} from "@adobe/react-spectrum";
import { useState } from "react";

export const DialogBox = () => {
  const [value, setValue] = useState("");
  return (
    <DialogTrigger>
      <ActionButton>Check connectivity</ActionButton>
      {(close) => (
        <Dialog>
          <Heading>Internet Speed Test</Heading>
          <Header>Connection status: Connected</Header>
          <Divider />
          <Content>
            <TextField value={value} onChange={setValue} />
          </Content>
          <ButtonGroup>
            <Button variant="secondary" onPress={close}>
              Cancel
            </Button>
            <Button variant="cta" onPress={close}>
              Confirm
            </Button>
          </ButtonGroup>
        </Dialog>
      )}
    </DialogTrigger>
  );
};

CodePudding user response:

Run setValue('') before closing

import {
  ActionButton,
  Button,
  ButtonGroup,
  Content,
  Dialog,
  DialogTrigger,
  Divider,
  Header,
  Heading,
  Text,
  TextField,
} from "@adobe/react-spectrum";
import { useState } from "react";

export const DialogBox = () => {
  const [value, setValue] = useState("");
  return (
    <DialogTrigger>
      <ActionButton>Check connectivity</ActionButton>
      {(close) => {
        const onClose = () => {
          setValue('')
          close()
        }
        return (
        <Dialog>
          <Heading>Internet Speed Test</Heading>
          <Header>Connection status: Connected</Header>
          <Divider />
          <Content>
            <TextField value={value} onChange={setValue} />
          </Content>
          <ButtonGroup>
            <Button variant="secondary" onPress={onClose }>
              Cancel
            </Button>
            <Button variant="cta" onPress={onClose }>
              Confirm
            </Button>
          </ButtonGroup>
        </Dialog>
        )
        }
      )}
    </DialogTrigger>
  );
};

CodePudding user response:

@Konrad Linkowski 's is good,
but I would recommend a better structure.
You can read from their docs about: handling events.

In the event handling you can add the setValue(''):

const cancel = (close) => {
    setValue('');
    close();
};
  • Related