Home > Software design >  How to conditionally render input box with key press
How to conditionally render input box with key press

Time:01-23

I have been building an URL Shortner. So in the front-end I am trying to build the input box like Cut.ly. For example, at first, I will have an empty input box with a Shorten button. When I post a Long URL and press submit it will conditionally render another input box with the short URL in it with a Copy Button. I've implemented that logic. Now what I want to do is in the Short URL input box whenever I do any keypress it will render the input box with the Shorten button. So, how can I Implement this logic? For reference, I'm posting a demo video.

enter image description here

Here's my code so far. I am using React Hook Form for Form management.

const CreateUrl = ({ match }) => {
  const [shortUrl] = useState('https://cutt.ly/wUBnKby');
  const [isSubmitted, setIsSubmitted] = useState(false);
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm({
    criteriaMode: 'all',
    mode: 'onChange',
  });

  const onSubmit = (data) => {
    console.log(data);
    reset('', {
      keepValues: false,
    });
    setIsSubmitted(true);
  };
  return (
    <div className="create__url">
      <Row>
        <Colxx xxs="12">
          <Breadcrumb heading="menu.createUrl" match={match} />
          <Separator className="mb-5" />
        </Colxx>
      </Row>
      <Row>
        <Colxx xxs="12" mt="4">
          {!isSubmitted ? (
            <form onSubmit={handleSubmit(onSubmit)}>
              <Row>
                <Colxx xs="12" lg="8">
                  <fieldset>
                    <input
                      name="url"
                      type="text"
                      placeholder="Paste long Url and Shorten it"
                      {...register('url', {
                        required: 'Url is Required',
                        pattern: {
                          value:
                            /[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\ ~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\ .~#?&//=]*)/i,
                          message: 'Please enter a valid Url',
                        },
                      })}
                    />
                    <ErrorMessage
                      errors={errors}
                      name="url"
                      render={({ messages }) =>
                        messages
                          ? Object.entries(messages).map(([type, message]) => (
                              <p className="error__message" key={type}>
                                <AiFillWarning style={{ marginTop: '-5px' }} />
                                <span>{message}</span>
                              </p>
                            ))
                          : null
                      }
                    />
                  </fieldset>
                </Colxx>
                <Colxx xs="12" lg="4">
                  <Button size="lg" type="submit">
                    {' '}
                    Submit
                  </Button>
                </Colxx>
              </Row>
            </form>
          ) : (
            <form>
              <Row>
                <Colxx xxs="12" lg="8">
                  <fieldset>
                    <input name="url" type="text" defaultValue={shortUrl} />
                  </fieldset>
                </Colxx>
                <Colxx xs="12" lg="4">
                  <Button size="lg" type="submit">
                    Copy
                  </Button>
                </Colxx>
              </Row>
            </form>
          )}
        </Colxx>
      </Row>
     </div>
  );
}

CodePudding user response:

Here you can use an empty array to store shortened URLs. When you press shorten URL button make the state true for that input field and use that array to show text in that field. I have implemented the same in my Shortly website. You can visit that for looking demo Shortly My GitHub repo has full source code for this website. That will help You a lot-- My GitRepo Hopes I am able to solve your Doubts......

CodePudding user response:

I have solved the logic. I put an onKeyUp even on the shortUrl input box and then track the keypress event with useState. Here's the code -

const CreateUrl = ({ match }) => {
  const [shortUrl, setShortUrl] = useState('');
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isKeyPressed, setIsKeyPressed] = useState(false);
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    criteriaMode: 'all',
    mode: 'onChange',
  });

  const onSubmit = (data) => {
    console.log(data);
    setIsSubmitted(true);
    setIsKeyPressed(false);
    setShortUrl('https://cutt.ly/wUBnKby');
  };

  return (
    <div className="create__url">
      <Row>
        <Colxx xxs="12">
          <Breadcrumb heading="menu.createUrl" match={match} />
          <Separator className="mb-5" />
        </Colxx>
      </Row>
      <Row>
        <Colxx xxs="12" mt="4">
          {!isSubmitted || isKeyPressed ? (
            <form onSubmit={handleSubmit(onSubmit)}>
              <Row>
                <Colxx xs="12" lg="8">
                  <fieldset>
                    <input
                      name="url"
                      type="text"
                      placeholder="Paste long Url and Shorten it"
                      {...register('url', {
                        required: 'Url is Required',
                        pattern: {
                          value:
                            /[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\ ~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\ .~#?&//=]*)/i,
                          message: 'Please enter a valid Url',
                        },
                      })}
                    />
                    <ErrorMessage
                      errors={errors}
                      name="url"
                      render={({ messages }) =>
                        messages
                          ? Object.entries(messages).map(([type, message]) => (
                              <p className="error__message" key={type}>
                                <AiFillWarning style={{ marginTop: '-5px' }} />
                                <span>{message}</span>
                              </p>
                            ))
                          : null
                      }
                    />
                  </fieldset>
                </Colxx>
                <Colxx xs="12" lg="4">
                  <Button size="lg" type="submit">
                    {' '}
                    Submit
                  </Button>
                </Colxx>
              </Row>
            </form>
          ) : (
            <form>
              <Row>
                <Colxx xxs="12" lg="8">
                  <fieldset>
                    <input
                      name="url"
                      type="text"
                      value={shortUrl}
                      onKeyUp={() => setIsKeyPressed(true)}
                    />
                  </fieldset>
                </Colxx>
                <Colxx xs="12" lg="4">
                  <Button size="lg" type="submit">
                    Copy
                  </Button>
                </Colxx>
              </Row>
            </form>
          )}
        </Colxx>
      </Row>
      {/* <Row className="mt-4">
        <Colxx xxs="12">
          {isSubmitted && (
       
          )}
        </Colxx>
      </Row> */}
    </div>
  );
};

  •  Tags:  
  • Related