Home > OS >  How to Disable Button if Form String Input is Empty React
How to Disable Button if Form String Input is Empty React

Time:01-20

I'm trying to disable a submit button on a form if the input text is empty, or if it's greater than 150 characters. For some reason it's working if the input is greater than 150 characters but not when it's empty and I'm not sure why. I've tried everything and I'm still stuck. I'm not sure if it's because I'm using Chakra UI or it's something else. Thank you in advance.

This is what I have:

const AddNewPost = () => {
const { isOpen, onOpen, onClose } = useDisclosure();
const [title, setTitle] = useState("");
const [isSaving, setSaving] = useState(false);

const handleSubmit = async () => {
    const date = new Date();

    await db.collection("posts").add({
        title,
        createdAt: date.toUTCString(),
        updatedAt: date.toUTCString(),
    });

    onClose();
    setTitle("");
};

return (
    <>
    <Button onClick={onOpen} colorScheme="blue">
        Add new post
    </Button>

    <Modal onClose={onClose} isOpen={isOpen} isCentered>
        <ModalOverlay>
            <ModalContent>
                <ModalHeader>Add new post</ModalHeader>
                <ModalCloseButton />
                <ModalBody>
                    <FormControl id="post-title">
                        <FormLabel>Post title</FormLabel>
                        <Textarea
                        type="post-title"
                        value={title}
                        onChange={(e) => 
                            {
                                if (e.target.value.length > 150) {
                                    window.alert("Message must not exceed 150 characters")
                                } else {
                                    setTitle(e.target.value)}
                                }
                                 
                            }
                            
                        />
                    </FormControl>
                </ModalBody>
                <ModalFooter>
                    <HStack spacing={4}>
                        <Button onClick={onClose}>Close</Button>
                        <Button
                        onClick={handleSubmit}
                        colorScheme="blue"
                        disabled={
                            !title || title.length > 150}
                        isLoading={isSaving}
                    >
                        Submit
                    </Button>
                    </HStack>
                </ModalFooter>
            </ModalContent>
        </ModalOverlay>
    </Modal>  
    </>
);

}; export default AddNewPost;

CodePudding user response:

According to the Chakra UI Button props documentation the button has no disabled prop.

The correct propname is isDisabled

isDisabled={title === "" || title.length > 150}
  • Related