Search code examples
javascriptcssreactjsstyled-componentsreact-final-form

How to reflect form validation error changes to CSS?


I have built a styled input component using the styled library and am having a hard time changing CSS of a component if the form field validation fails.

<Form onSubmit={onSubmit}>
    {({ handleSubmit, submitting, submitFailed, hasValidationErrors, form }) => (
      <form
        onSubmit={(e) => {
          this.setState({ submitSucceeded: false });
          handleSubmit(e).then((err) => {
            if (err) {
              if (onSubmitError) {
                onSubmitError(err[FORM_ERROR]);
              }
              return;
            }
            form.reset();
            this.setState({ submitSucceeded: true });
            if (onSubmitSuccess) {
              onSubmitSuccess();
            }
          });
        }}
      >
        <Grid container justify="center" spacing={1}>
          <Grid item xs={12}>
            <Field name="businessName" validate={composeValidators(requiredValidator)}>
              {({ input, meta }) => (
                <Fragment>
                  <StyledInput placeholder={businessNamePlaceholder} required {...input} />
                  <StyledFieldError meta={meta} />
                </Fragment>
              )}
            </Field>
          </Grid>

What I intend to do is change the styled component StyledInput border to red in case form validation fails.

The CSS looks like:

import styled from 'styled-components';

export const StyledInput = styled.input`
  width: 100%;
  padding: 8px;
  background-color: #ffffff;
  box-shadow: inset 0 1px 2px 0 rgba(201, 202, 200, 0.5);
  border-color: ##Dynamic value based on form input validation##;
`;

I have looked in styled components and it gives me a way to pass props. I feel I should used that but I am new to javascript and react and don't know how to achieve that. I am using import { Form, Field } from 'react-final-form';


Solution

  • You can add prop validationFailed to StyledInput component.

    <StyledInput validationFailed={true} placeholder={businessNamePlaceholder} required {...input} />
    

    And then in styled component.

    export const StyledInput = styled.input`
      border-color: ${props => props.validationFailed ? "red" : "transparent";
    `;