Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to set Cookie in ReactJS ?

  • Difficulty Level : Basic
  • Last Updated : 16 Dec, 2020

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:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!