Search code examples
javascriptcssreactjstypescriptstyled-components

Styled Component For Forms


I am using this form with material-ui components. Instead of writing the inline style that I am currently using for width, I wanted to opt for css-in-js. I have used styled-components previously but I don't think there's a form element with that.

The only example I came across was one where they had used built-in styled component labels. Since I have implemented validation on these material ui text fields as well so I don't want to change the structure. What would be the suitable way to put the style in css-in-js. I would prefer if there's a solution with styled-components.

          return (
            <div className="main-content">
              <form
                style={{ width: '100%' }}
                onSubmit={e => {
                  e.preventDefault();
                  submitForm(email);
                }}>
                <div>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    name="email"
                    helperText={touched.email ? errors.email : ''}
                    error={touched.email && Boolean(errors.email)}
                    label="Email"
                    value={email}
                    onChange={change.bind(null, 'email')}
                  />
                  <CustomButton
                    disabled={!isValid || !email}
                    text={'Remove User'}
                  />
                </div>
              </form>
            </div>
          );

Solution

  • just make the styled form:

    import styled from 'styled-components';
    
    const Form = styled.form`
       width: 100%;
    `;
    
    

    and use it:

        return (
                <div className="main-content">
                  <Form
                    onSubmit={e => {
                      e.preventDefault();
                      submitForm(email);
                    }}>
                    <div>
                      <TextField
                        variant="outlined"
                        margin="normal"
                        id="email"
                        name="email"
                        helperText={touched.email ? errors.email : ''}
                        error={touched.email && Boolean(errors.email)}
                        label="Email"
                        value={email}
                        onChange={change.bind(null, 'email')}
                      />
                      <CustomButton
                        disabled={!isValid || !email}
                        text={'Remove User'}
                      />
                    </div>
                  </Form>
                </div>
              );