How to use bcrypt in react js?

Hi Friends πŸ‘‹,

Welcome To aHoisting!

To use bcrypt in react js, you have to install "bcryptjs" and than import "bcrypt" from "bcryptjs" and then you have use hash function from bcrypt that how you can use bcryptjs in react js.

Today, I am going to show you, how to use bcrypt in react js.

Installation

Install the following packages to use bcryptjs in react js.

npm

npm install bcryptjs

yarn

yarn add bcryptjs

Table of contents

  • Install and create a new React app.
  • Import react component.
  • Create a Component.

Let’s start with the first step.

Step 1: Install and create a new React app.

First you have to install the React project. You should use create-react-app command to create a new React project.

npx create-react-app my-app
cd my-app
npm start

Step 2: Import react component.

After installing, you have to import your React component.

import React, { useState } from "react";
import bcrypt from "bcryptjs";

Step 3: Create a Component.

You can use {String.fromCharCode(169)} to use bcrypt in react js.

<input
  type="password"
  value={password}
  onChange={(e) => setPassword(e.target.value)}
  placeholder="Enter password"
/>
<button onClick={handleHashPassword}>Hash Password</button>
  {hashedPassword && (
    <div>
      <h4>Hashed Password:</h4>
        <textarea readOnly value={hashedPassword} rows="3" cols="50" />
        </div>
  )}

Use bcrypt example.

The below code is an example of a React. you have to install "bcryptjs" and than import "bcrypt" from "bcryptjs" to use bcrypt in react js.

App.js

import React, { useState } from "react";
import bcrypt from "bcryptjs";

function App() {
  const [password, setPassword] = useState("");
  const [hashedPassword, setHashedPassword] = useState("");

  const handleHashPassword = async () => {
    const saltRounds = 10; // Number of salt rounds
    const hash = await bcrypt.hash(password, saltRounds);
    setHashedPassword(hash);
  };

  return (
    <div>
      <h3>Hash a Password</h3>
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="Enter password"
      />
      <button onClick={handleHashPassword}>Hash Password</button>
      {hashedPassword && (
        <div>
          <h4>Hashed Password:</h4>
          <textarea readOnly value={hashedPassword} rows="3" cols="50" />
        </div>
      )}
    </div>
  );
}

export default App;

In the above code example, I have used the "bcryptjs" to use bcrypt in react js.

Check the output of the above code.

React, use, bcrypt

All the best πŸ‘