Home > Software design >  how show input only if checkbox is cheked? Reac | next.js
how show input only if checkbox is cheked? Reac | next.js

Time:06-08

I try to manage this task but I don’t understand how should I do.

I want to show the promo code field only if the checkbox(I have promo code) is checked.

Also, it would be great to show this field use js method, not CSS style display:none

Please help if you have any idea

Maybe it should be simle function with if else?

import React from "react";
import { useState } from "react";
import { Box, Button, chakra, Link, Stack, VStack } from "@chakra-ui/react";
import { Heading } from "@/components/shared/Heading";
import { FieldError, useForm } from "react-hook-form";
import FormInput from "@/components/base/form/FormInput";
import FormRadioCard from "@/components/base/form/FormRadioCard";
import NextLink from "next/link";
import composeValidations, {
  validations,
} from "../../base/form/validations/formValidations";
import FormCheckbox from "@/components/base/form/FormCheckbox";
import { UseFormRegisterReturn } from "react-hook-form/dist/types/form";
import { LeadFormAnswers } from "@/components/lead-form/form/useLeadForm";
import IncentiveBubble from "@/components/base/IncentiveBubble";
import FormPhoneNumber from "@/components/base/form/FormPhoneNumber";

const LINK_SEPARATOR = "{{link}}";

const PrivacyPolicyCheckbox: React.FC<PrivacyPolicyCheckboxProps> = ({
  registerProps,
  link,
  error,
  text,
}) => {
  const sentenceParts = text.split(LINK_SEPARATOR);
  const firstPart = sentenceParts[0];
  const secondPart = sentenceParts[1];

  return (
    <FormCheckbox
      error={error}
      registerProps={registerProps}
      px={[5, 8]}
      mt={6}
    >
      {firstPart}
      <NextLink href={link.href} passHref>
        <Link color="blue.400" target="_blank">
          {link.title}
        </Link>
      </NextLink>
      {secondPart}
    </FormCheckbox>
  );
};


const emailValidation = composeValidations(
  validations.requiredEmail,
  validations.rejectForbiddenDomains,
  validations.rejectDisposableEmails
);

const Row: React.FC = ({ children }) => (
  <Stack gap={6} w="full" direction={["column", "row"]}>
    {children}
  </Stack>
);

const EmbeddedRow: React.FC<{ embedded?: boolean }> = ({
  children,
  embedded,
}) => {
  if (embedded) {
    return <Row>{children}</Row>;
  }

  return <>{children}</>;
};

const LeadFormFirstPage: React.VFC<LeadFormFirstPageProps> = ({
  onSubmit,
  embedded,
  title,
  emailLabel,
  emailForbiddenDomainErrorLink,
  numberOfEmployeesLabel,
  numberOfEmployeesOptions,
  privacyPolicyText,
  privacyPolicyLink,
  submitText,
  bubbleText,
  promoCodeText,
  promoCodeLabel,
}) => {
  const {
    register,
    formState: { errors },
    handleSubmit,
    control,
    setValue,
  } = useForm<LeadFormAnswers>();

  return (
    <Box>
      <Heading px={[5, 8]} level={3} mb={8} fontWeight={600}>
        {title}
      </Heading>
      <Box
        as={chakra.form}
        onSubmit={handleSubmit((data) => {
          if (!embedded) {
            window.scrollTo({ top: 0 });
          }
          onSubmit(data);
        })}
      >
        <VStack gap={6} alignItems="flex-start" px={[5, 8]}>
          <EmbeddedRow embedded={embedded}>
            <FormInput
              w="full"
              label={emailLabel}
              error={errors.email}
              errorParams={{ link: emailForbiddenDomainErrorLink }}
              registerProps={register("email", emailValidation)}
            />
          </EmbeddedRow>
                  </VStack>
        <FormRadioCard
          label={numberOfEmployeesLabel}
          name="numberOfEmployees"
          control={control}
          options={numberOfEmployeesOptions}
        />
        <PrivacyPolicyCheckbox
          error={errors.consent}
          registerProps={register("consent", validations.required)}
          text={privacyPolicyText}
          link={privacyPolicyLink}
        />
        <VStack gap={6} alignItems="flex-start" px={[5, 8]}>
          <FormCheckbox
            mt={6}
            label={promoCodeText}
            registerProps={register("checkbox")}
          >
            {promoCodeText}
          </FormCheckbox>
          <Row>
            <FormInput
              w="full"
              label={promoCodeLabel}
              registerProps={register("promoCode")}
            />
          </Row>
        </VStack>
        <IncentiveBubble
          text={bubbleText}
          variant="transparent"
          mt={[6, 10]}
          px={[5, 8]}
        >
          <Button variant="primary" size="M" type="submit">
            {submitText}
          </Button>
        </IncentiveBubble>
      </Box>
    </Box>
  );
};

type LinkProps = { title: string; href: string };
export type LeadFormFirstPageProps = {
  onSubmit(data: LeadFormAnswers): void;
  embedded?: boolean;
  title: string;
  emailLabel: string;
  emailForbiddenDomainErrorLink: string;
  numberOfEmployeesLabel: string;
  numberOfEmployeesOptions: string[];
  privacyPolicyText: PrivacyPolicyCheckboxProps["text"];
  privacyPolicyLink: PrivacyPolicyCheckboxProps["link"];
  submitText: string;
  bubbleText: string;
  promoCodeText: string;
  promoCodeLabel: string;
};

export default LeadFormFirstPage;

CodePudding user response:

hope this example helps you understanding how to toggle a state of an element with useState :

import { useState } from "react";

export default function App() {
  const [isChecked, setIsChecked] = useState(false);
  return (
    <div className="App">
      <input
        type="checkbox"
        defaultChecked={isChecked}
        onClick={() => setIsChecked(!isChecked)}
      />
      {isChecked ? "text is shown" : "text should be hidden"}
    </div>
  );
}

CodePudding user response:

Here is a simple approach where we have the checkbox then the text input field of the promo code. We use the checked value of the checkbox to show/hide the promo code field.

import React, { useState } from "react";

export default function CheckBoxExample() {
  // checked state and the onChange method
  const [hasPromo, setHasPromo] = useState(false);
  const onChangeCheckBox = (e) => {
    setHasPromo(e.target.checked);
  };

  // the promo code input field value and the onChange method
  const [promo, setPromo] = useState("");
  const onChangePromo = (e) => {
    setPromo(e.target.value);
  };

  return (
    <div>
      <form>
        <input type="checkbox" checked={hasPromo} onChange={onChangeCheckBox} />

        {hasPromo && (
          <input type="text" value={promo} onChange={onChangePromo} />
        )}
      </form>
    </div>
  );
}

  • Related