Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
How do I activate the submit button conditionally?

I have made a web app where you can upload images via an image url. Here is the link: https://meme-gallery-web-app.netlify.app/

The problem is if I press the submit button where the form is empty, it still posts an empty image data to database.

My question is how can I activate the button only when there's a proper image ur? Only when a proper image url is submitted in the form, then the button will activate and I can submit it. Here is the code where I handle the form request.

import { FormControl, Input, Button } from "@chakra-ui/react";
import axios from "axios";
import React from "react";
import { baseUrl } from "../config";

class SubmitLink extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      url: "",
    };
  }

  onInputChange = (event) => {
    this.setState({
      url: event.target.value,
    });
  };
// where I make post request. 
  onClick = () => {
    axios
      .post(`${baseUrl}/submitlink`, {
        url: this.state.url,
      })
      .then((response) => {
        console.log(response);
        this.props.onSuccessfulUpload();
        this.setState({
          url: "",
        });
      })
      .catch(function (error) {
        console.log(error);
      });
  };

  render() {
    return (
      <FormControl>
        <Input
          type='url'
          value={this.state.url}
          onChange={this.onInputChange}
          width={{
            base: "70%",
            md: "55%",
            xl: "60%",
          }}
          ml={{
            base: "5%",
            md: "5%",
            xl: "4%",
          }}
        />
        <Button
          ml={2}
          mb={1}
          colorScheme='teal'
          type='submit'
          onClick={this.onClick}
          size='md'
        >
          Submit
        </Button>
      </FormControl>
    );
  }
}

export default SubmitLink;

here's the API where I handle the post request

// post api for saving images from URL

const imageModel = require("../models/models.js");

//ignore the date variables. haven't properly implemented it. 
var date = new Date();
var currentDate = date.toLocaleDateString();

const submitLink = async (req, res) => {
  let saveImageFromUrl = new imageModel();
  saveImageFromUrl.img.data = req.body.url;
  saveImageFromUrl.postedAt = currentDate;
  await saveImageFromUrl.save(function (err, result) {
    if (err) return console.error(err);
    else {
      res.sendStatus(202);
    }
  });
};

module.exports = submitLink;

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could disable the button while checking if the url is valid or not

Something like this:

const isUrlValid = () => {
  const { url } = this.state;
  const res = url.match(
    /(http(s)?:\/\/.)?(www\.)?[\w#%+.:=@~-]{2,256}\.[a-z]{2,6}\b([\w#%&+./:=?@~-]*)/g
  );
  if (res == null) return false;
  return true;
};

//...JSX Body

<Button
  ml={2}
  mb={1}
  colorScheme="teal"
  type="submit"
  onClick={this.onClick}
  size="md"
  disabled={isUrlValid()}
>
  Submit
</Button>;

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda