• Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

TypeError: invalid assignment to const "x"

The JavaScript exception "invalid assignment to const" occurs when it was attempted to alter a constant value. JavaScript const declarations can't be re-assigned or redeclared.

What went wrong?

A constant is a value that cannot be altered by the program during normal execution. It cannot change through re-assignment, and it can't be redeclared. In JavaScript, constants are declared using the const keyword.

Invalid redeclaration

Assigning a value to the same constant name in the same block-scope will throw.

Fixing the error

There are multiple options to fix this error. Check what was intended to be achieved with the constant in question.

If you meant to declare another constant, pick another name and re-name. This constant name is already taken in this scope.

const, let or var?

Do not use const if you weren't meaning to declare a constant. Maybe you meant to declare a block-scoped variable with let or global variable with var .

Check if you are in the correct scope. Should this constant appear in this scope or was it meant to appear in a function, for example?

const and immutability

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in case the content is an object, this means the object itself can still be altered. This means that you can't mutate the value stored in a variable:

But you can mutate the properties in a variable:

Javatpoint Logo

  • Interview Q

ReactJS Tutorial

Interview Questions

JavaTpoint

React.js has revolutionized web development by providing a declarative and component-based approach to building user interfaces. With its powerful ecosystem and robust design principles, React allows developers to create complex applications efficiently. One crucial feature in React is the use of 'const,' a keyword that plays a significant role in maintaining immutability and predictability within components. In this article, we'll explore the concept of 'const' in React.js and how it is used to manage states and props.

In JavaScript, 'const' is a keyword used to declare variables that cannot be reassigned after their initial assignment. When you declare a variable using 'const,' its value remains constant throughout its scope. This behavior is beneficial for preventing accidental reassignment of values and helps maintain code integrity.

In React, the state represents the mutable data within a component that can change during its lifetime. Traditionally, developers used the 'class' component syntax and the 'setState' method to manage the state. However, with the introduction of React Hooks, functional components can now handle state using the 'useState' hook. Here's how 'const' plays a crucial role in managing the state:

In this example, the 'useState' hook declares the 'count' variable using 'const.' Although 'count' can change its value using 'setCount,' the 'const' keyword ensures that 'count' itself remains immutable and cannot be directly reassigned.

Props (short for properties) are read-only data passed from parent components to child components. In functional components, props are also defined using 'const,' allowing components to receive data from their parent component. Here's a simple example:

Using 'const' with Props:

In this example, the 'name' prop is declared as a 'const' in the 'MyChildComponent.' This ensures that the child component cannot modify the prop directly, maintaining a unidirectional data flow and enhancing the predictability of the application.

Declaring variables with 'const' enforces immutability, making it easier to track and reason about your code. Immutable variables are essential for reducing bugs and side effects. By using 'const' for state and props, you ensure that components remain predictable, leading to a more straightforward debugging process and a better understanding of code behavior. 'const' makes code more readable, as readers can quickly identify variables that should not change within the scope. Immutable data structures and variables allow React to optimize rendering by performing shallow comparisons for changes, reducing the overall rendering workload.
While 'const' provides numerous benefits, it's essential to understand its limitations and when to use it appropriately: 'const' ensures that the reference to an object or array cannot be changed, but it does not prevent changes to the object's properties or array elements. To achieve deep immutability, you may need to use helper libraries like Immutable.js or write custom functions for deep cloning. In class components, 'const' can still be used for declaring variables, but it won't offer the same benefits related to functional components and React Hooks. For state management, 'const' is more commonly used in functional components with hooks. While 'const' promotes immutability, excessive use of 'const' may lead to a large number of variables in the component's scope, potentially affecting performance. Care

In addition to using 'const' with the 'useState' hook, React offers alternative ways to manage state:

This hook is suitable for managing more complex state logic and is a more advanced alternative to 'useState.' It follows the same principles of immutability and can be combined with 'const' for variable declarations. For larger applications with complex state requirements, external state management libraries like Redux or MobX can be used. These libraries allow you to centralize and manage the application state efficiently.

In ReactJS, const is a keyword used to declare constants. Constants are variables whose values cannot be changed or reassigned once they are initialized. React developers often use const to declare variables that should remain constant throughout the component's lifecycle.

Here's how const is used in ReactJS:

You can use the const keyword to declare a constant variable in ReactJS. Once a value is assigned to a constant, you cannot change it later in the code.

Constants are useful when you want to define some values that are reused throughout your React components. For example, you might use a constant to store a URL endpoint, API key, or any other fixed value.

Declaring constants improves code readability and maintainability. When you use a constant, it becomes easier to understand the purpose and meaning of the value you are using. Additionally, if you ever need to update the value, you only need to do it in one place (where the constant is declared), and it will automatically update throughout your application.

Constants are block-scoped, which means they are only accessible within the block they are defined in. For example, if you declare a constant within a function, it will be accessible only within that function.

Keep in mind that while the value of a constant cannot be changed, the value itself can be mutable if it is an object or an array. For example:

To ensure immutability for complex objects or arrays, you may consider using additional techniques like Object.freeze() or using libraries like Immutable.js.

You can use const with a destructuring assignment to extract values from objects or arrays while making those extracted values constant.

You can use const in combination with conditional statements to initialize a constant based on a condition.

You can use const in function parameters to ensure that the parameter remains constant within the function.

When using const with JSX in React components, you can define JSX elements as constants and use them in the component's return statement.

Using const for values that don't change can have some performance benefits. Since the constant values are determined at compile-time, it can help the JavaScript engine optimize the code better.

However, keep in mind that using const for large objects or arrays may not always provide performance benefits, especially if the object's properties or array elements are frequently being modified.

While const is useful for declaring constants, it's important to remember that it doesn't make objects or arrays immutable. If you need to ensure immutability for complex objects or arrays, consider using libraries like Immutable.js or other immutable data structures.

Also, when you know that a value needs to be changed or reassigned later in your code, it's better to use let instead of const. const should only be used when you want to enforce that a value should remain constant throughout its scope.

The 'const' keyword plays a critical role in React.js for maintaining immutability and predictability within components. By using 'const' for state and props, developers can create more reliable and maintainable applications. Embracing this approach ensures that components remain self-contained, making them easier to test, debug, and understand. Incorporating 'const' into your React.js projects is a powerful step towards building scalable and efficient applications.





Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

TypeError: Assignment to constant variable when using React useState hook

Abstract: Learn about the common error 'TypeError: Assignment to constant variable' that occurs when using the React useState hook in JavaScript. Understand the cause of the error and how to resolve it effectively.

If you are a React developer, you have probably come across the useState hook, which is a powerful feature that allows you to manage state in functional components. However, there may be times when you encounter a TypeError: Assignment to constant variable error while using the useState hook. In this article, we will explore the possible causes of this error and how to resolve it.

Understanding the Error

The TypeError: Assignment to constant variable error occurs when you attempt to update the value of a constant variable that is declared using the const keyword. In React, when you use the useState hook, it returns an array with two elements: the current state value and a function to update the state value. If you mistakenly try to assign a new value to the state variable directly, you will encounter this error.

Common Causes

There are a few common causes for this error:

  • Forgetting to invoke the state update function: When using the useState hook, you need to call the state update function to update the state value. For example, instead of stateVariable = newValue , you should use setStateVariable(newValue) . Forgetting to invoke the function will result in the TypeError: Assignment to constant variable error.
  • Using the wrong state update function: If you have multiple state variables in your component, make sure you are using the correct state update function for each variable. Mixing up the state update functions can lead to this error.
  • Declaring the state variable inside a loop or conditional statement: If you declare the state variable inside a loop or conditional statement, it will be re-initialized on each iteration or when the condition changes. This can cause the TypeError: Assignment to constant variable error if you try to update the state value.

Resolving the Error

To resolve the TypeError: Assignment to constant variable error, you need to ensure that you are using the state update function correctly and that you are not re-declaring the state variable inside a loop or conditional statement.

If you are forgetting to invoke the state update function, make sure to add parentheses after the function name when updating the state value. For example, change stateVariable = newValue to setStateVariable(newValue) .

If you have multiple state variables, double-check that you are using the correct state update function for each variable. Using the wrong function can result in the error. Make sure to match the state variable name with the corresponding update function.

Lastly, if you have declared the state variable inside a loop or conditional statement, consider moving the declaration outside of the loop or conditional statement. This ensures that the state variable is not re-initialized on each iteration or when the condition changes.

The TypeError: Assignment to constant variable error is a common mistake when using the useState hook in React. By understanding the causes of this error and following the suggested resolutions, you can overcome this issue and effectively manage state in your React applications.

References
[1] React Documentation:
[2] MDN Web Docs:

Tags: :  javascript reactjs react-state

Latest news

  • Handling Multiple Self-Referencing Foreign Keys in Hibernate: A MySQL Table Approach
  • Chrome's New GeminiNano API: What Languages are Supported?
  • Sum Columns: Get Values on Y-axis in Python
  • Azure AC Not Pulling Images from Public Docker Registry: Possible Bug?
  • Next.js 14 Middleware Issue: Handling Auth and Validation
  • Understanding Default Values and Nil in TypeScript
  • Upgrading from Spring Boot 2.7.18 to 3.3: Redis Properties Issues in Production
  • Setting up a Pop-up Child Checkout Page in WooCommerce
  • Nginx Timeout: Handling Multiple Pages on One Host with Different Tabs in CentOS
  • Using AppThemeBinding to Display Different Images in .NET MAUI
  • Applying Security to SSAS: Multiple Dimensions without Considering Facts
  • WordPress Child Theme Stylesheet Not Loading: A Solution
  • Exploring Samtools HTSJDK: Finding a Specific Range in a File
  • Migrating NX Monorepo for Non-Application Projects: Open-Sourcing Testing Tools and Templating Library
  • Debugging Expo App Crashes After Installation on Android
  • Implementing SweepPrune in C++ for 3D Physics Engine with OpenGL
  • Addressing Unexpected Background Fill in Chart.js Line Chart
  • Parsing SQL Scripts with Python: Working with Table Fields 'name' and 'table' comes
  • Scaling Fill Manual: Adding a Second Legend Line to a Graph
  • Error with Date Parameter Type in Online Assessment Function
  • Flutter App Runs Great on Android but Displays Blank Screen in Web Version
  • Custom CSS Global Styles Not Applying in WordPress: A Solution
  • Trying to Run Llama3 but Unavailable: An Alternative Suggestion
  • Using Laravel's CASE clause for Supplying Data with Subqueries
  • Troubleshooting Unreadable Error Messages in PostgreSQL on Windows 11
  • Best Way to Send Multiple Images via API: One Call per Image or One Call for All?
  • Combining Multiple Rows Based on Index in SQL: A Practical Example
  • Drawing a Monochrome Matrix Image using Cairo in Software Development
  • Creating a Directory in C#: A UPSERT Operation
  • Mongoose Encryption: Handling App Crashes with Express, express-encryption, and Mongoose-Encryption
  • Accessing Kubernetes Cluster Logs via Alloy Loki and Grafana (version 10.x)
  • Training YOLOv5 Model on SageMaker with S3 Bucket Data over 100GB
  • Creating Amortization Tables with Excel and VBA for Prepayments and Unearned Revenues
  • Can Microfrontend Modules Run Independently Without the Host Application?
  • Handling Already Commented Code Blocks in React
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • Web Technology

How to declare constant in react class ?

To declare a constant that can be accessed in a React class component, there are multiple approaches that could be efficiently implemented such that constant is accessible class-wide. Constants can be declared in the following two ways:

  • Create a getter method in the class for getting the constant when required.
  • Assign the class constant after the declaration of the class. 

Create a sample project with the following command:

Now move to the constantDemo folder using the following command:

The Project Structure will look like the following:

assignment to constant variable in react js

Filename: App.js Now open the App.js file and paste the following code in it:

Now run the project using the following command:

Output : 

assignment to constant variable in react js

Another way of declaring the constants is shown below. Paste down the following code in the App.js file.

Filename: App.js

assignment to constant variable in react js

Please Login to comment...

Similar reads.

  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

How to define constants in React?

In this article, we explain how to define and use constants in React to make your code more maintainable and reusable.

In React, you can define constants using the const keyword. For example:

This creates a constant named MY_CONSTANT with the value "hello". Constants are like variables, except that their value cannot be changed once they are assigned.

You can use constants in React to store values that don't change, such as configuration options or static data that you want to reference in your code.

Here's an example of how you might use a constant in a React component:

In this example, the constant API_ENDPOINT is used to store the URL of an API endpoint. This constant is then used in the fetch call to retrieve data from the API.

It's important to note that constants in React are only available within the scope in which they are defined. In the example above, the MY_CONSTANT constant would only be available within the MyComponent function. If you want to use a constant in multiple components, you would need to define it in a separate file and import it into the components that need it.

Overall, constants can be a useful tool for organizing and managing your code in React. They can help you avoid hardcoding values and make your code more maintainable and reusable.

November 06, 2022

November 03, 2022

Java-Script How-Works

Online courses on JavaScript programming

How and Why to Use “const” in React Components?

React development code

  • Danielle Johnson
  • No comment yet
  • November 2, 2023

In the guide below, the intricacies of utilizing constants in React for enhanced code maintainability and reusability are unraveled.

In the React framework, constants can be introduced using the `const` declaration. Take a look at this illustration:

Here, a constant called GREETING_MESSAGE is initialized with the string “hello”. While constants bear resemblance to variables, a defining characteristic is their immutable nature post assignment.

Table of Contents

Why Use Constants?

Utilizing constants in React is beneficial for storing invariant values, like configuration settings or static datasets, ensuring a standardized reference throughout the codebase.

Practical Application in a React Component

To visualize the application of constants, consider this React component:

In this depiction, DATA_ENDPOINT stores an API’s URL and is subsequently utilized to fetch data.

Scope and Availability

A crucial thing to remember is the scope-bound nature of constants in React. Drawing from the demonstration, the GREETING_MESSAGE constant is strictly available within the confines of the SampleComponent function. To broaden a constant’s accessibility across components, it’s advisable to centralize its definition in an individual file and then import it wherever necessary.

To further emphasize the importance and advantages of constants, let’s delve deeper into the realm of React development.

Constants as a Pillar of Consistency

  • A consistent codebase is every developer’s dream. Constants act as an anchor, ensuring that developers don’t drift away into a sea of hard-coded values. By centralizing these constants, not only is the codebase more readable, but it also becomes less prone to errors. Imagine having to change a value scattered across multiple files. With constants, it’s a change in one place, and the ripple effect covers the entire application;
  • In team settings, where multiple developers contribute to the same codebase, constants play a pivotal role in setting a standard. When one developer establishes a constant, others can seamlessly use it without any ambiguity. This synergy prevents overlapping work, miscommunications, and possible code conflicts;
  • React’s ecosystem encourages the use of immutable data structures, and constants align perfectly with this philosophy. Once set, they remain unchanged, reducing the risk of unintentional modifications that could introduce bugs or vulnerabilities.

Future-Proofing the Code

As applications evolve, requirements change. Constants provide a robust foundation that can adapt to these changes. By isolating these values, developers can easily update, refactor, or extend functionalities without sifting through layers of intertwined code.

In essence, integrating constants into React development is not just a best practice—it’s a testament to a developer’s commitment to quality, consistency, and forward-thinking.

Concluding Thoughts

To sum up, the strategic employment of constants in React is instrumental in fortifying code structure, preventing value hardcoding, and paving the way for a maintainable and reusable codebase.

Leave a Reply Cancel reply

You must be logged in to post a comment.

How to concatenate Strings and Variables in React

avatar

Last updated: Apr 7, 2024 Reading time · 3 min

banner

# Concatenate strings and variables in React

Use a template literal to concatenate strings and variables in React, e.g. "<a href={ https://example.com/${myPath} }".

Template literals are delimited with backticks and allow us to embed variables and expressions using the dollar sign and curly braces ${expression} syntax.

And here is the CSS for the examples.

react concatenate string and variable

We used template literals to concatenate strings and variables in React.

The dollar sign and curly braces syntax allows us to use placeholders that get evaluated.

The curly braces we wrapped the template literal in mark the beginning of an expression that gets evaluated.

You can also use template literals outside of your JSX code.

You can even call functions in template literals.

By default, a template literal concatenates the parts into a string.

# Conditionally concatenate a string and a variable

If you need to conditionally concatenate a string and a variable, use the ternary operator in your template literal.

The ternary operator is very similar to an if/else statement.

If the expression to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise, the value to the right of the colon is returned.

You can imagine that the value before the colon is the if block and the value after the colon is the else block.

The ternary operator in the example checks if the length of the string hi is equal to 2 .

If the condition is met, the operator returns the string bg-yellow , otherwise, an empty string is returned.

Here is an example that concatenates a string and variable if a state variable is set to true .

And here is the CSS for the example.

We set the onClick prop on the button element, so every time the button is clicked a function is invoked.

Inside the function, we simply toggle the state of the isActive boolean .

We used the ternary operator to check if the state variable is equal to true .

If the isActive state variable is equal to true , the string to the left of the colon gets returned, otherwise, the string to the right of the colon is returned.

The dollar sign and curly braces syntax will be evaluated if the condition is met and the string and variable will get concatenated to form the element's class name.

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript const.

The const keyword was introduced in ES6 (2015)

Variables defined with const cannot be Redeclared

Variables defined with const cannot be Reassigned

Variables defined with const have Block Scope

Cannot be Reassigned

A variable defined with the const keyword cannot be reassigned:

Must be Assigned

JavaScript const variables must be assigned a value when they are declared:

When to use JavaScript const?

Always declare a variable with const when you know that the value should not be changed.

Use const when you declare:

  • A new Array
  • A new Object
  • A new Function
  • A new RegExp

Constant Objects and Arrays

The keyword const is a little misleading.

It does not define a constant value. It defines a constant reference to a value.

Because of this you can NOT:

  • Reassign a constant value
  • Reassign a constant array
  • Reassign a constant object

But you CAN:

  • Change the elements of constant array
  • Change the properties of constant object

Constant Arrays

You can change the elements of a constant array:

But you can NOT reassign the array:

Constant Objects

You can change the properties of a constant object:

But you can NOT reassign the object:

Difference Between var, let and const

ScopeRedeclareReassignHoistedBinds this
varNoYesYesYesYes
letYesNoYesNoNo
constYesNoNoNoNo

What is Good?

let and const have block scope .

let and const can not be redeclared .

let and const must be declared before use.

let and const does not bind to this .

let and const are not hoisted .

What is Not Good?

var does not have to be declared.

var is hoisted.

var binds to this.

Browser Support

The let and const keywords are not supported in Internet Explorer 11 or earlier.

The following table defines the first browser versions with full support:

Chrome 49 Edge 12 Firefox 36 Safari 11 Opera 36
Mar, 2016 Jul, 2015 Jan, 2015 Sep, 2017 Mar, 2016

Advertisement

Block Scope

Declaring a variable with const is similar to let when it comes to Block Scope .

The x declared in the block, in this example, is not the same as the x declared outside the block:

You can learn more about block scope in the chapter JavaScript Scope .

Redeclaring

Redeclaring a JavaScript var variable is allowed anywhere in a program:

Redeclaring an existing var or let variable to const , in the same scope, is not allowed:

Reassigning an existing const variable, in the same scope, is not allowed:

Redeclaring a variable with const , in another scope, or in another block, is allowed:

Variables defined with var are hoisted to the top and can be initialized at any time.

Meaning: You can use the variable before it is declared:

This is OK:

Variables defined with const are also hoisted to the top, but not initialized.

Meaning: Using a const variable before it is declared will result in a ReferenceError :

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

CSS Variables for React Devs

Introduction.

This is a controversial opinion , but I rather like CSS-in-JS. 😬🚨

But! I also really like CSS. And I don't believe that using CSS-in-JS absolves you from needing to learn it. You're writing CSS either way! It's just packaged a little bit differently.

No matter where you put your CSS, it behooves you to develop a mastery of the language. Becoming better at CSS will make you a more effective front-end developer.

In this tutorial, we're going to see how to take advantage of one of the most exciting newer developments in CSS: CSS variables , AKA Custom Properties. We'll see how we can use them in our React apps to improve our workflows and do some pretty fancy stuff.

Link to this heading Why though?

As a React developer, you might be thinking that you don't need variables in CSS. You have an entire JavaScript engine at your disposal!

There are two reasons to switch to CSS variables in your React app:

  • The ergonomics are nice.
  • It unlocks new possibilities! You can do things with CSS variables that are not possible with JS.

Let's look at how to use them, and then we'll see what doors get unlocked!

Link to this heading Quick intro

Let's look at CSS variables in action:

Code Playground

In this example, we're defining a new variable, --highlight-color , on the paragraph selector. We're using that color to apply a background color to child <em> elements. Whenever an <em> is used within a paragraph, it'll have a yellow background.

Notice how we define our CSS variables in the same way that we define typical CSS properties. This is because CSS variables are properties . They're officially called "CSS Custom Properties", and for good reason!

CSS variables are inheritable by default, just like font-size or color . When we define a variable on an element, it is available to all of that element's children.

Many developers believe that CSS variables are global, but this isn't quite right. Consider this:

The em inside this heading sets background to var(--highlight-color) , but it has no effect, because --highlight-color hasn't been defined for this element. It's only been defined for paragraphs, and this <em> tag is not within a paragraph.

Sometimes, we want our CSS variables to be global. For example, CSS variables are often used for color themes, and in this case, we want the colors to be available across the application.

We can do this by hanging our variables on the top-level element, <html> :

The thing that makes CSS variables different from typical CSS properties is that we can access their values , using the var() function. This is what allows us to use CSS custom properties as variables.

Some other quick facts about CSS variables:

Link to this heading In a React app

Let's see what this looks like in React. This tutorial uses styled-components , but the instructions should be relatively similar regardless of the CSS-in-JS library.

First, I'm going to assume that you have a file that holds all of your design tokens, something like this:

In a React app, you might import them directly into the components that need them:

Or, you might use a theme:

Here's the same code, but set up using CSS variables:

(If you're not familiar with createGlobalStyle , it allows us to write unscoped CSS, as if we were writing it in a styles.css file.)

We've created some variables, hung them on the root node, and now we can access them in our components:

This is a nice little win, in my opinion. Being able to access theme values without an import or an inline function is a breath of fresh air. You do lose some static typing benefits—more on this later—but it's a very happy tradeoff in my eyes.

This is a relatively minor difference, though. Let's look at something more interesting…

Link to this heading Changing values, not variables

So let's say we have a Button component.

It looks alright, but we get feedback that the click target is too small on mobile devices: industry guidelines are that interactive elements should be between 44px and 48px tall . We need to bump up the size to make it easier to tap on phones.

Let's walk through a possible solution, not using CSS variables.

Two quick notes about this code:

We ship this change, and we sleep a little bit better knowing that we've improved the usability of our app.

We quickly learn that our work isn't done, however. Buttons are not the only tappable elements in our apps! There's also text inputs, among others.

Let's update our TextInput component as well. To keep things DRY, we'll store our sizes on our theme:

We use those values in both of our components:

This is a significant chunk of CSS to be lugging around to any tappable element!

Now, we could solve this in a number of ways, using a styled-component mixin or a CSS class. But I think the best way to solve this problem is with CSS variables.

Instead of imperatively specifying how each component should respond at different breakpoints, what if we passed it a reactive variable that tracked that for us?

With this magic CSS variable, our responsive components get so much simpler:

I'll be the first to admit: the first time you see this pattern, it seems a bit funky. It requires a mental model shift. But it's super compelling, in my opinion!

We're all used to using CSS media queries to apply a different chunk of CSS in different scenarios. But what if we kept the CSS properties the same, and changed the values ?

Inside our components, min-height always points to the same value, --min-tap-target-height , but that value is dynamic .

Let's look at some of the benefits:

The "Principle of Least Knowledge" is the idea that code should only have access to stuff directly adjacent to it, and not "reach over" into a totally different part of the codebase. I feel like if we squint a little, that same idea applies here.

Another quick example: we can do the same trick for our theme variables, so that each viewport has its own scale.

instead of having the same scale for every window size, we can have custom scales for each breakpoint. This leads to much more consistent user interfaces, and much less fussing around inside each individual component.

Link to this heading Other new possibilities

So far, everything we've talked about is about the developer experience. We've looked at alternative ways to solve problems.

Let's look now at some of the problems that CSS variables are uniquely equipped to solve, leading to improved user experiences.

Link to this heading Animate any property

There are some CSS properties that simply can't be animated. If you've ever tried to animate a linear or radial gradient, for example, you've realized pretty quickly that it doesn't work.

With CSS variables, you can animate any property , because you aren't applying the transition to the property, you're applying the transition to the value .

For example, here's a fun gradient animation, made possible with CSS variables:

Read more about this button in my tutorial, "Magical Rainbow Gradients" .

Link to this heading “Dark Mode” flash fix

If you've tried to implement a "Dark mode" variant, you've probably been bitten by this tricky situation: for a brief moment, the wrong colors flash:

"Dark Mode" is surprisingly tricky, especially in a server-rendered context (like with Next.js or Gatsby). The problem is that the HTML is generated long before it reaches the user's device, so there's no way to know which color theme the user prefers.

We can solve this with CSS variables and a dash of cleverness. I wrote about this approach in my blog post, The Quest for the Perfect Dark Mode .

Link to this heading Getting and Setting

In the example above, we hardcode our theme values in a GlobalStyles component:

There may be times where you need to access these values in JavaScript.

If you'd like, you can keep storing them in a constants.js file. They'll be used to instantiate the CSS variables, but then also imported wherever you need the raw values in JS:

Another idea, though, is to use CSS as the source of truth. You can access the values with a bit of JS:

You can set those values from within JS as well:

Link to this heading Drawbacks

Link to this heading no types.

Probably the biggest downside to using CSS variables for themes is that there's no way to statically type them (via Typescript or Flow).

In my mind, this isn't a huge deal; I've been on both sides of this river. Having a typed theme object is nice, but I can't say that it's saved me a ton of time. Generally, it's obvious when you mistype the name of a CSS variable, and it's a quick fix.

I think it's important to run compile-time checks on your site, but I think tools like Chromatic are a much more reliable check. They run in CI and capture any differences in the rendered visual output.

That said, if type-safety is a must-have, you don't have to give it up! You'd just need to keep your styles in a JS object, and interpolate them in. This tweet from Fatih Kalifa shows how he set up his types for CSS variables.

Link to this heading Browser support

CSS variables enjoy healthy browser support amongst the 4 leading browsers, but it's missing IE support:

Link to this heading Not as loose

When using styled-components, you can put variables wherever you want, including within media queries:

CSS variables can't be used anywhere within media queries. There is chatter around letting users describe their own environment variables with env() , which would allow for this… But it has yet to materialize.

Despite these drawbacks, however, CSS variables open a lot of really interesting doors. I've been using them for a few years now (including on this very blog!) and I love them. They're my preferred way to manage dynamic styles.

Link to this heading The holy trinity

As web developers, we work with 3 primary technologies: HTML, CSS, and JS. In order to work effectively, we need to be comfortable with all 3.

I know lots of devs who have a pretty solid grasp of HTML and JS, but who struggle with CSS. I was in this group myself, for years!

CSS is a deceptively complex language. The basics can be learned quickly and (relatively) easily, but it's an incredibly difficult language to master.

When we write CSS, we're only seeing the tip of the iceberg. It's a very implicit language. All sorts of secret mechanisms leap into action, tweaking the effects of our CSS properties in surprising, inscrutable ways.

CSS doesn't have error messages or console logs. We write CSS, and either the result is what we expect, or it isn't. When things go wrong, it can make us feel powerless. We wind up throwing random CSS properties at the wall, hoping one of them will do what we want.

I want to help. I recently released a CSS course, CSS for JavaScript Developers . It's built specifically for folks who use a JS framework like React. It teaches you how CSS actually works, to build out your mental model so that you develop an intuition for the language.

It's not like other courses you've taken. There are over 150 videos, but it's not a video course. It's an interactive, multi-modality, self-paced adventure. There are plenty of exercises, real-world-inspired projects, and even a few mini-games. It uses a custom-built platform which is unlike anything you've used before.

If you struggle with CSS, I hope you'll check it out. Gaining confidence with CSS is game-changing, especially if you're already comfortable with HTML and JS. When you complete the holy trinity, it becomes so much easier to stay in flow, to truly enjoy developing web applications.

Learn more here: https://css-for-js.dev

Last Updated

February 22nd, 2024

A front-end web development newsletter that sparks joy

My goal with this blog is to create helpful content for front-end web devs, and my newsletter is no different! I'll let you know when I publish new content, and I'll even share exclusive newsletter-only content now and then. No spam, unsubscribe at any time.

If you're a human, please ignore this field.

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeError: Assignment to constant variable. #16211

@lidaof

lidaof commented Jul 25, 2019

or report a ?
bug

TypeError: Assignment to constant variable.

System: OSX
npm: 6.10.2
node: v10.13.0
react: 16.8.6

@artuross

artuross commented Jul 26, 2019 • edited Loading

What I think you're trying to is something like this:

something = 1; something = 2;

Even though the path implies that the error happens in react, I think the error happens in your code, but it's difficult to tell from a single line. Perhaps you could share a little bit more (error stack)?

Sorry, something went wrong.

lidaof commented Jul 26, 2019

Hi , thank you so much for reply. Sure, here is the screenshot:

I don't think I did that const thing....my code is

@jquense

jquense commented Jul 26, 2019

the error is coming from your code so there is either a typo/bug in what you've written or a problem compiling it. In either case it's not realted to React, and the React issue tracker is for React bugs. I'd recommend bisecting your code, commenting out bits and pieces until the error goes away and you can narrow down which part specifically is breaking it.

@jquense

Hi ok....so the problem only happens on build version, it's not happening in development version.......so the code should be fine....

artuross commented Jul 27, 2019

I would look at lines 112 and 126 at .

@shahchaitanya

shahchaitanya commented Jul 29, 2019

I am facing a similar issue today. did you find out a solution to fix it?

lidaof commented Jul 29, 2019

I am not sure if we have same condition, I updated typescript to 3.4 and create-react-app to 2.1 solved this problem.

  • 👍 1 reaction

are you using uglify js plugin in Production? This problem is occurred due to this plugin. are referred to this bug. I solved this issue by adding in uglify js object.

  • 👍 3 reactions
  • 🎉 2 reactions
  • ❤️ 4 reactions
  • 🚀 1 reaction

lidaof commented Jul 30, 2019

Thank you for reply . I think i did use it, but I don't know where to put this option. I was using react-app-rewire with react-scripts-ts

shahchaitanya commented Jul 30, 2019

you can configure your web pack in webpack.config.js file. I put this option under webpack.config.js.

thank you . I tried that but it's not working for me. Thanks again.

@prasenpatil2107

prasenpatil2107 commented Oct 10, 2019

I think there is a simple catch.....if you define it as const you cant change its value. To resolve it just define it by let and try. I was going through a similar error solved it by this.

  • 👍 2 reactions
  • 👎 9 reactions

@jannunen

jannunen commented Sep 18, 2021

You just saved my day (after 10 hours of fiddling).

@ghost

ghost commented Oct 25, 2021

Knock Knock, I am also facing the same problem. 😄

  • 😄 1 reaction

No branches or pull requests

@jannunen

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Assignment to constant variable

I try to read the user input and send it as a email. But when I run this code it gives me this error: Assignment to constant variable.

jonrsharpe's user avatar

You might want:

I would think the latter option is better, at least stylistically.

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged node.js nodemailer or ask your own question .

  • The Overflow Blog
  • How to build open source apps in a highly regulated industry
  • Community Products Roadmap Update, July 2024
  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • What makes a homepage useful for logged-in users
  • The [lib] tag is being burninated

Hot Network Questions

  • Plausible reasons for the usage of Flying Ships
  • Line from Song KÄMPFERHERZ
  • Why can't LaTeX (seem to?) Support Arbitrary Text Sizes?
  • Could someone translate & explain the Mesorah?
  • Name this kimberling center
  • Understanding symbol of a latching push switch
  • Should "as a ..." and "unlike ..." clauses refer to the subject?
  • I want to leave my current job during probation but I don't want to tell the next interviewer I am currently working
  • PCB layout for 16 MHz crystal oscillator
  • y / p does not paste all yanked lines
  • Are there examples of triple entendres in English?
  • Is there a drawback to using Heart's blood rote repeatedly?
  • Will 2.1" schwalbe MTB tire in 25mm rim become wider that 2.25" in 19mm rim?
  • Measure by mass vs. 'Spooned and Leveled'
  • In equation (3) from lecture 7 in Leonard Susskind’s ‘Classical Mechanics’, should the derivatives be partial?
  • Is there a way to do artificial gravity testing of spacecraft on the ground in KSP?
  • Factor-smooth interactions in generalized additive models
  • Books using the axiomatic method
  • Is it unfair to retroactively excuse a student for absences?
  • Can you help me to identify the aircraft in a 1920s photograph?
  • What does it mean if Deutsche Bahn say that a train is cancelled between two instances of the same stop?
  • Did the BBC censor a non-binary character in Transformers: EarthSpark?
  • Wait a minute, this *is* 1 across!
  • Why is pressure in the outermost layer of a star lower than at its center?

assignment to constant variable in react js

IMAGES

  1. How to declare const array in React js?

    assignment to constant variable in react js

  2. React Native

    assignment to constant variable in react js

  3. How to declare constant in react class ?

    assignment to constant variable in react js

  4. JavaScript features die je moet kennen als je React wil beheersen

    assignment to constant variable in react js

  5. TypeError: Assignment to Constant Variable in JavaScript

    assignment to constant variable in react js

  6. How To Store Value In Variable In React Js

    assignment to constant variable in react js

VIDEO

  1. Average Assignment 02

  2. volatile and constant variable in c || how to modify value of constant variable || Rahul Sir

  3. CONSTANT AND VARIABLE / WHAT IS TERM / class 6,7,8,9,10 math #math #class10maths

  4. JavaScript variable assignment const variable

  5. Make Your JavaScript Constants Immutable ⚠️ #javascript #javascripttutorials #javascripttutorial

  6. The Correct way to Manage Form State in react js

COMMENTS

  1. javascript

    Maybe what you are looking for is Object.assign(resObj, { whatyouwant: value} ). This way you do not reassign resObj reference (which cannot be reassigned since resObj is const), but just change its properties.. Reference at MDN website. Edit: moreover, instead of res.send(respObj) you should write res.send(resObj), it's just a typo

  2. type error = assignment to constant variable react.js

    Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company Visit the blog

  3. TypeError: Assignment to Constant Variable in JavaScript

    To solve the "TypeError: Assignment to constant variable" error, declare the variable using the let keyword instead of using const. Variables declared using the let keyword can be reassigned. The code for this article is available on GitHub. We used the let keyword to declare the variable in the example. Variables declared using let can be ...

  4. TypeError: invalid assignment to const "x"

    For instance, in case the content is an object, this means the object itself can still be altered. This means that you can't mutate the value stored in a variable: js. const obj = { foo: "bar" }; obj = { foo: "baz" }; // TypeError: invalid assignment to const `obj'. But you can mutate the properties in a variable:

  5. ES6 Variables in React.js

    In this blog post, we'll explore how to use these new types of variables in your React.js projects. ... // This works fine b = 5; // This also works c = 6; // Error: Assignment to constant variable

  6. React ES6 Variables

    It does not define a constant value. It defines a constant reference to a value. Because of this you can NOT: Reassign a constant value; Reassign a constant array; Reassign a constant object; But you CAN: Change the elements of constant array; Change the properties of constant object

  7. Const in ReactJS

    React developers often use const to declare variables that should remain constant throughout the component's lifecycle. Here's how const is used in ReactJS: 1. Declaring Constants: You can use the const keyword to declare a constant variable in ReactJS. Once a value is assigned to a constant, you cannot change it later in the code.

  8. TypeError: Assignment to constant variable when using React useState hook

    TypeError: Assignment to constant variable when using React useState hook If you are a React developer, you have probably come across the useState hook, which is a powerful feature that allows you to manage state in functional components.

  9. How to declare constant in react class

    In JavaScript, you can declare a constant variable using the const keyword. The const keyword is used to create variables whose values should not be reassigned once they are initially set. Example: Here, pi is a constant variable, and its value is set to 3.14. Once a value is assigned to a constant variable using const, you cannot change that value

  10. How to define constants in React?

    In React, you can define constants using the const keyword. For example: const MY_CONSTANT = "hello"; This creates a constant named MY_CONSTANT with the value "hello". Constants are like variables, except that their value cannot be changed once they are assigned. You can use constants in React to store values that don't change, such as ...

  11. Unraveling the Use of const in React Development

    When one developer establishes a constant, others can seamlessly use it without any ambiguity. This synergy prevents overlapping work, miscommunications, and possible code conflicts; React's ecosystem encourages the use of immutable data structures, and constants align perfectly with this philosophy. Once set, they remain unchanged, reducing ...

  12. How to concatenate Strings and Variables in React

    If the isActive state variable is equal to true, the string to the left of the colon gets returned, otherwise, the string to the right of the colon is returned. The dollar sign and curly braces syntax will be evaluated if the condition is met and the string and variable will get concatenated to form the element's class name.

  13. JavaScript const

    Constant Objects and Arrays. The keyword const is a little misleading. It does not define a constant value. It defines a constant reference to a value. Because of this you can NOT: Reassign a constant value; Reassign a constant array; Reassign a constant object; But you CAN: Change the elements of constant array; Change the properties of ...

  14. How to use CSS variables with React

    Learn how to use CSS variables with React to create dynamic themes, fluid animations, and responsive layouts. This tutorial by Josh W Comeau, a web developer and educator, will show you how to get the most out of CSS-in-JS tools like styled-components, and how to rethink media queries with custom properties.

  15. TypeError: Assignment to constant variable. #16211

    TypeError: Assignment to constant variable. System: OSX npm: 6.10.2 node: v10.13. react: 16.8.6. Do you want to request a feature or report a bug? bug What is the current behavior? TypeError: Assignment to constant variable. System: OSX npm: 6.10.2 node: v10.13. react: 16.8.6 ... false in uglify js compress object.

  16. How to Add a Constants File to Your React Project

    Another way to solve this would be to write something like: import {EXISTINGACCOUNTURL as NEWACCOUNTURL} from './constants'. … in order to create an alias for your first constant when you import ...

  17. NodeJS TypeError: Assignment to Constant Variable

    In Node.js, the "TypeError: Assignment to Constant Variable" occurs when there's an attempt to reassign a value to a variable declared with the const keyword. In JavaScript, const is used to declare a variable that cannot be reassigned after its initial assignment.

  18. javascript

    Unable to declare constant in react class Hot Network Questions Since water is a molecule, can the aerosol sprayed through double slit form interference pattern?

  19. node.js

    Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.