Search code examples
javascriptreactjsvalidationreact-bootstrapstyled-components

Validating Non Empty String for Styled Components in React


I'm currently using the styled-components library in React for a Form. The component sends a POST request when a "Create" Button is clicked.

import { Form, Button } from "react-bootstrap";
import React, { useState, useEffect } from "react";
import styled from "styled-components";

const StyledInput = styled(Form.Control)`
  padding: 2px 5px;
  width: 150px;
  margin-right: 20px;
  height: 50px;
`;

function Builder() {

const [name, setName] = useState("");

 return (
    <GridWrapper>
      <h1>Builder</h1>
      <Form>
        <Form.Row>
          <Form.Group controlId="name" bssize="large">
            <Form.Label>Probet Name</Form.Label>
            <StyledInput
              size="sm"
              required
              value={name}
              type="String"
              onChange={(e) => setName(e.target.value)}
              className="smaller-input"
            />
          </Form.Group>
        </Form.Row>
      </Form>
      <Button type="submit" onClick={handleSubmit}>
        Create
      </Button>
    </GridWrapper>
  );
}

My question is, I have passed the `required` prop into the `StyledInput` component, yet when I click on the "Create" `Button` it still sends through an empty String. Is there a quick way to validate this using `styled-components` or do I have to write something myself in the `handleSubmit` function?   

Solution

  • Move the Button of type="submit" inside of the Form so the validation occurs. As for the submission, you can handle this using the onSubmit prop of Form instead of handling it on the click of the Button

    <Form onSubmit={handleSubmit}>
      <Form.Row>
        <Form.Group controlId="name" bssize="large">
          <Form.Label>Probet Name</Form.Label>
          <StyledInput
            size="sm"
            required
            value={name}
            type="String"
            onChange={(e) => setName(e.target.value)}
            className="smaller-input"
          />
        </Form.Group>
      </Form.Row>
      <Button type="submit">
        Create
      </Button>
    </Form>
    

    Note that if you are performing additional logic before submission or are performing XHR instead of redirection, you can opt to use preventDefault on the event object when handling the submission

    Example:

    <Form onSubmit={(e)=>handleSubmit(e)}>
    
    function handleSubmit(e) {
      e.preventDefault();
      //some logic
    }
    

    Lastly, you are using hooks (i.e., const [name, setName] = useState("")) outside of a Functional Component's body. This will cause errors - I suggest to move it inside of function Builder