How To Implement PasswordRevealer In ReactJS

How To Implement PasswordRevealer In ReactJS

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>
);

Source Code

Below are the screenshots of how the outputs for both the show and hide password looks like:

Screenshot from 2022-04-20 17-36-07.png

Screenshot from 2022-04-20 17-36-10.png

Thanks for reading...

Happy Coding!