Search code examples
reactjsreact-jsonschema-forms

react json form schema form - Password hide/Show availability


Using react json form schema form and for the 'Password' field, I have used the "ui:widget": "password" in the uiSchema. Additionally i wanted to add either to show or hide the password.


Solution

  • Here's another json schema renderer which can hide password with dots. The benefit is in code autocompletion: you don't need to google answers, IDE knows everything you need

    Link to the playground

    screenshot

    import { TypedField, FieldType } from "react-declarative";
    
    import { Button } from '@mui/material';
    
    export const fields: TypedField[] = [
      {
        type: FieldType.Outline,
        fields: [
          {
            type: FieldType.Typography,
            typoVariant: 'h6',
            placeholder: 'Sign in',
          },
          {
            type: FieldType.Text,
            name: 'email',
            inputType: 'email',
          },
          {
            type: FieldType.Text,
            name: 'password',
          },
          {
            type: FieldType.Component,
            sx: {
              mt: '35px',
            },
            element: ({  email, password }) => (
              <Button variant="contained" onClick={() => alert(JSON.stringify({ email, password }))}>
              Next
              </Button>
            ),
          }
        ]
      }
    ]
    
    

    I found a way to toggle password visibility: to show different input field

    import { TypedField, FieldType } from "react-declarative";
    
    import { Visibility, VisibilityOff } from '@mui/icons-material';
    
    export const fields: TypedField[] = [
        {
             type: FieldType.Text,
             isVisible: ({ showPassword }) => {
                return !showPassword;
             },
             inputType: 'password',
             name: 'password',
             trailingIcon: Visibility,
             trailingIconClick: (value, data, payload, onValueChange, onChange) => {
                onChange({
                    showPassword: !data.showPassword,
                });
             },
        },
        {
            type: FieldType.Text,
            isVisible: ({ showPassword }) => {
                return !!showPassword;
            },
            inputType: 'text',
            name: 'password',
            trailingIcon: VisibilityOff,
            trailingIconClick: (value, data, payload, onValueChange, onChange) => {
                onChange({
                    showPassword: !data.showPassword,
                });
             },
        },
    ];