Thursday, November 28, 2024
Google search engine
HomeLanguagesJavascriptHow to set Cookie in ReactJS ?

How to set Cookie in ReactJS ?

Cookies are an important part of an application because cookies are used to set value in a key-value form which can be set in browser storage and used further for identifying the current user. The following example shows how to set the cookie in the ReactJS application, here we have taken the username as key, which is set in the cookie with its value.

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app setcookiedemo

Step 2: After creating your project folder i.e. setcookiedemo, move to it using the following command:

cd setcookiedemo

Project Structure: It will look like the following.

Project Structure

App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code to set cookies in localStorage with basic UI.

Javascript




import React, { useState } from "react";
  
const App = () => {
  
  const [message, setMessage] = useState('')
    
  const setCookieFunction = (value) => {
    
    localStorage.setItem('username', value)
  
    setMessage('Username set as cookie!!')
  }
  
  return (
    <div style={{
      marginLeft: '200px',
    }}>
      <pre>
        <h2>Setting Cookie in ReactJS</h2>
        <span>Enter User Name: </span><input type="text" 
        onChange={(e) => setCookieFunction(e.target.value)}></input> <br />
        <span style={{
          fontWeight: 'bold',
          color: 'red',
        }}>{message}</span>
      </pre>
    </div>
  );
}
  
export default App


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

  1. The following will be the output if the user enters a username which is set as a cookie as shown below:

  2. Now go to your localStorage of browser by inspecting the browser page, there you can see our cookie which is set with key=’username’ and value=’gouravhammad’ as shown below:

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments