Render a password input field with a reveal button.
Use the React.useState()
hook to create the shown state variable and set its value to false. Use a<div>
to wrap both the<input>
and the <button>
element that toggles the type of the input field between "text"
and "password"
.
Code Samples:
PasswordRevealer.js
import React from "react";
import "./PasswordRevealer.css";
function PR({ value }) {
const [shown, setShown] = React.useState(false);
return (
<div className="PasswordRevealer">
<input
type={shown ? "text" : "password"}
value={value}
onChange={() => {}}
/>
<button onClick={() => setShown(!shown)}>Show/Hide</button>
</div>
);
}
export default PR;
index.js
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import PR from "./PasswordRevealer";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<PR />
</React.StrictMode>
);
Below are the screenshots of how the outputs for both the show and hide password looks like:
Thanks for reading...
Happy Coding!