'how to reveal/unrveal password inside input in Data Driven Forms (it npm react package)?
I have a custom form imported from node_module as import FormRenderer from "@data-driven-forms/react-form-renderer/form-renderer";
this form requires schema in json object to then convert them to html element, I want to add icon and onClick functionality to show the password using this form?
schema = {
name: "password",
label: "Password",
type: "password",
component: componentTypes.TEXT_FIELD,
placeholder: "Password",
placeholdericon: "/images/lock.svg",
},
Solution 1:[1]
You need a component that supports this functionality. In this case we need a custom component.
Have a look at this codepen for an example.
import React, { useState } from "react";
import FormRenderer from "@data-driven-forms/react-form-renderer/form-renderer";
import useFieldApi from "@data-driven-forms/react-form-renderer/use-field-api";
import useFormApi from "@data-driven-forms/react-form-renderer/use-form-api";
const Button = ({ children, label, ...props }) => (
<button {...props}>{label}</button>
);
const FormTemplate = ({ formFields }) => {
const { handleSubmit, onCancel } = useFormApi();
return (
<form
onSubmit={(event) => {
event.preventDefault();
handleSubmit();
}}
>
{formFields}
<Button type="submit" label="Submit" />
<Button type="button" label="cancel" onClick={onCancel} />
</form>
);
};
const Password = (props) => {
const {
customProp,
label,
input,
isRequired,
meta: { error, touched },
icon,
...rest
} = useFieldApi(props);
const [hidden, hide] = useState(true);
return (
<div>
<label htmlFor={input.name}>
{isRequired && <span>* </span>}
{label}
</label>
<input
type={hidden ? "password" : "text"}
id={input.name}
{...input}
{...rest}
/>
<button onClick={() => hide(!hidden)} type="button">
{icon} {hidden ? "Show" : "Hide"}
</button>
{touched && error && <p>{error}</p>}
</div>
);
};
const componentMapper = {
password: Password,
};
const schema = {
fields: [
{
component: "password",
name: "password",
label: "Your password",
icon: "?",
},
],
};
const ComponentMapper = () => {
return (
<FormRenderer
componentMapper={componentMapper}
FormTemplate={FormTemplate}
schema={schema}
onSubmit={(values) => console.log(values)}
onCancel={() => console.log("cancel action")}
/>
);
};
export default ComponentMapper;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Henry Ecker |