Using destructuring assignment in React

by Nathan Sebhastian

Posted on Nov 19, 2020

Reading time: 3 minutes

assignment 1 react components

Destructuring assignment is a feature of JavaScript introduced by ES6 (or ES 2015) that’s available for both object and array data types. It allows you to assign the values of an array or the properties of an object without needing to reference the variable directly in the assignment.

Here’s the traditional way of assigning a value to a variable in JavaScript:

With destructuring assignment, your code will look like this:

You just turned two lines of assignment into one. Awesome, right? The same is also possible with an array, but instead of using curly brackets( {} ) you need to use square brackets ( [] ) on the assignment:

In fact, the useState hook from React returns an array with two values that we destructure immediately. Here’s an illustration of how it works:

The benefits of using destructuring assignment is especially visible when using React because you would deal with state and props frequently. For example, a functional component may receive a single prop object with many properties like this:

When you need to display the props in your interface, you’d probably pass the prop into the component and use the value with props. syntax:

Yikes! Look at how long the syntax just for displaying a name. When using destructuring assignment, you can reduce that long syntax and make it better. First, destructure the userData props before passing it to the component:

Then pass it into the component as two props:

Or you can also use spread operator so you don’t need to destructure it:

Then immediately destructure the props object when you define the parameters in the function, like this:

And now you can use the arguments inside your props with less repetition:

Want even less repetition? You can even destructure nested properties with JavaScript!

Here’s a Code Sandbox example that you can tweak with.

The syntax looks a bit complicated at first, so here’s how to make destructuring easy in two steps process:

First, you need to find the name of the properties you want to extract first. In the example, the goal is to extract loggedIn , firstName , lastName , and email properties:

First and Second-level properties in JS object

After that, you simply find the first-level properties that hold the second-level properties. Write the property name:

Then write the desired properties inside the curly brackets:

The same could also be applied in class-based components. You simply destructure the props in your render() function:

And that’s it. Destructuring assignment is a wonderful feature from ES6 that really helps you to avoid repetition and keep your code clean. You can extract nested properties of an object and simply use them inside your render function.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials. Learn statistics, JavaScript and other programming languages using clear examples written for people.

Learn more about this website

Connect with me on Twitter

Or LinkedIn

Type the keyword below and hit enter

Click to see all tutorials tagged with:

React Tutorial

React hooks, react exercises.

You can test your React skills with W3Schools' Exercises.

We have gathered a variety of React exercises (with answers) for each React Chapter.

Try to solve an exercise by filling in the missing parts of a code. If you're stuck, hit the "Show Answer" button to see what you've done wrong.

Count Your Score

You will get 1 point for each correct answer. Your score and total score will always be displayed.

Start React Exercises

Start React Exercises ❯

If you don't know React, we suggest that you read our React Tutorial from scratch.

Get Certified!

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

DEV Community

DEV Community

Sathish Kumar N

Posted on May 15, 2023

Part 1: Naming Conventions - The Foundation of Clean Code

Welcome to the first part of my blog series, "React Best Practices in 2023." In this blog, we will delve into the crucial topic of naming conventions and how they serve as the foundation of clean and maintainable code in React.

Naming conventions play a vital role in improving code readability , maintainability , organization , and communication . They help create a cohesive and structured codebase that is easier to work with, reduces errors , and promotes collaboration among developers.

In this part, we will focus specifically on naming conventions in React. We will explore the recommended approaches for naming components, variables, functions, and other identifiers within your React projects. You'll gain insights into the popular conventions such as PascalCase , camelCase , kebab-case and SCREAMING_SNAKE_CASE , and understand when and where to apply them.

We will also discuss the benefits of meaningful and descriptive names that accurately reflect the purpose and functionality of the elements in your code.

Pascal Case

Pascal Case typically refers to the convention of writing compound words in which the first letter of each word is capitalized and there are no spaces or punctuation marks between the words.

In React, we can use pascal case for below elements:

1. React Component

2. CSS Class Names

3. Enumerations

Camel case refers to the convention of writing compound words or phrases where each word begins with a capital letter except the first word , which starts with a lowercase letter.

In React, we can use camel case for below elements:

1. Variable Names

2. Function Names

3. Object Properties

4. CSS Module Class Names

5. Custom Hooks

6. Higher Order Component

Kebab case refers to the convention of writing compound words in lowercase letters and separating them with hyphens ("-").

In React, we can use kebab case for below elements:

1. CSS Class Names

2. Folder Names

SCREAMING_SNAKE_CASE

SCREAMING_SNAKE_CASE refers to the convention of writing compound words or phrases in uppercase letters , with words separated by underscores ("_").

1. Constants

2. Enumeration Properties

3. Global Variables

Higher-Order Component Naming Convention

Here are best practices for naming Higher-Order Component:

1. Use "with" as Prefix

Common convention is to use the prefix "with" followed by the functionality or purpose of the HOC.

2. Use "Original Component" as Suffix

Include the original component name in the HOC's name to indicate the component it is enhancing or wrapping

Custom Hooks Naming Convention

Here are best practices for naming custom hooks:

1. Use "use" as Prefix

Common convention is to use the prefix "use" followed by the functionality or purpose of the Custom Hooks.

2. Use "Behaviour of hook" as Suffix

Name the custom hooks that accurately describes the purpose or behaviour of the custom hook.

Use more descriptive and specific names

It's important to avoid using generic or unclear names for your components, variables, or functions.

Let's take an example to illustrate this:

In the above example, The component name, variable name "data" and the function name "onClick" are generic and don't convey their specific purpose or context .

To improve clarity and maintainability, it's recommended to use more descriptive and specific names.

Here's an best practice:

In the improved example, the component is renamed to "ProductDetails", which clearly indicates its purpose. The variable name "productInfo" conveys that it holds detailed information about a product. The function name "addProductToCart" describes its action of adding the product to the shopping cart.

By using descriptive and meaningful names, it becomes easier for other developers (including yourself) to understand and maintain the code in the long run.

Choosing Singular or Plural Naming

The decision to use singular or plural names for various elements, such as components, variable and functions, can significantly impact code clarity .

Let's take an example:

By aligning the singular or plural form of component, function and variable names with their intended purpose, we improve code readability and facilitate better understanding for other developers working on the codebase.

Avoid Excessive Abbreviations

Here's an example that demonstrates the importance of avoiding excessive abbreviations in code:

In the above example, the object selUsr contains selected user information with abbreviated property names like usrId , usrNm , and usrEmail . While this code may be functional, it lacks clarity and can cause confusion for other developers who need to work with this object and property.

In this example, the property names userId , userName , and userEmail are more descriptive, providing a clearer understanding of the data being used. This makes the code easier to read , maintain , and collaborate on, contributing to better overall code quality .

That concludes our exploration of naming conventions in React.js. By following these best practices, you are well-equipped to create clean , readable , and maintainable code in your React projects.

Remember, choosing meaningful and descriptive names for your variables, functions, components, and other elements is essential for enhancing code clarity and improving collaboration among developers. Consistency in naming conventions throughout your project will make your codebase more organized and easier to understand.

In the next part of our series, we will delve into the critical topic of folder structure in React. We'll discuss how to organize your project's files and directories effectively, and how to implement a modular approach that promotes code reusability and maintainability.

Stay tuned for next post!

Happy coding!😊👩‍💻👨‍💻

Top comments (7)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

withmussy profile image

  • Location Iran,Tehran
  • Work frontend js developer
  • Joined Nov 13, 2019

Thanks, Sathish, Your advice resonated with me, and I'm excited to apply it to enhance my code. Keep up the great work! 👍💻

sathishskdev profile image

  • Location Chennai, Tamil Nadu
  • Work Lead Software Engineer at Disprz
  • Joined May 5, 2023

Thank you for your comment! It's always fulfilling to receive such positive feedback.

yehanny profile image

  • Location Antioquia, Colombia
  • Work Freelance
  • Joined May 29, 2019

Great post and good convention for naming everything in React, thanks

Thank you for your comment!

patzi275 profile image

  • Education Institut de Formation et de Recherche en Informatique
  • Joined Dec 26, 2022

Very informative

minozzzi profile image

  • Joined Aug 22, 2020

I believe that in the selected User object the properties also don't need the user prefix, which makes them redundant

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

rustcodeweb profile image

jQuery Tutorials

Rustcode - Apr 4

18xdeveloper profile image

News admin dashboard

Sheikh Abdur Rohit - Mar 31

devshi profile image

Creating Your First Backend with Node.js: Step-by-Step Guide in 2024

Devshi Bambhaniya - Apr 1

dillonheadley profile image

HTMZ inspired form subission

Dillon Headley - Mar 31

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Quick Start

Welcome to the React documentation! This page will give you an introduction to the 80% of React concepts that you will use on a daily basis.

You will learn

  • How to create and nest components
  • How to add markup and styles
  • How to display data
  • How to render conditions and lists
  • How to respond to events and update the screen
  • How to share data between components

Creating and nesting components

React apps are made out of components . A component is a piece of the UI (user interface) that has its own logic and appearance. A component can be as small as a button, or as large as an entire page.

React components are JavaScript functions that return markup:

Now that you’ve declared MyButton , you can nest it into another component:

Notice that <MyButton /> starts with a capital letter. That’s how you know it’s a React component. React component names must always start with a capital letter, while HTML tags must be lowercase.

Have a look at the result:

The export default keywords specify the main component in the file. If you’re not familiar with some piece of JavaScript syntax, MDN and javascript.info have great references.

Writing markup with JSX

The markup syntax you’ve seen above is called JSX . It is optional, but most React projects use JSX for its convenience. All of the tools we recommend for local development support JSX out of the box.

JSX is stricter than HTML. You have to close tags like <br /> . Your component also can’t return multiple JSX tags. You have to wrap them into a shared parent, like a <div>...</div> or an empty <>...</> wrapper:

If you have a lot of HTML to port to JSX, you can use an online converter.

Adding styles

In React, you specify a CSS class with className . It works the same way as the HTML class attribute:

Then you write the CSS rules for it in a separate CSS file:

React does not prescribe how you add CSS files. In the simplest case, you’ll add a <link> tag to your HTML. If you use a build tool or a framework, consult its documentation to learn how to add a CSS file to your project.

Displaying data

JSX lets you put markup into JavaScript. Curly braces let you “escape back” into JavaScript so that you can embed some variable from your code and display it to the user. For example, this will display user.name :

You can also “escape into JavaScript” from JSX attributes, but you have to use curly braces instead of quotes. For example, className="avatar" passes the "avatar" string as the CSS class, but src={user.imageUrl} reads the JavaScript user.imageUrl variable value, and then passes that value as the src attribute:

You can put more complex expressions inside the JSX curly braces too, for example, string concatenation :

In the above example, style={{}} is not a special syntax, but a regular {} object inside the style={ } JSX curly braces. You can use the style attribute when your styles depend on JavaScript variables.

Conditional rendering

In React, there is no special syntax for writing conditions. Instead, you’ll use the same techniques as you use when writing regular JavaScript code. For example, you can use an if statement to conditionally include JSX:

If you prefer more compact code, you can use the conditional ? operator. Unlike if , it works inside JSX:

When you don’t need the else branch, you can also use a shorter logical && syntax :

All of these approaches also work for conditionally specifying attributes. If you’re unfamiliar with some of this JavaScript syntax, you can start by always using if...else .

Rendering lists

You will rely on JavaScript features like for loop and the array map() function to render lists of components.

For example, let’s say you have an array of products:

Inside your component, use the map() function to transform an array of products into an array of <li> items:

Notice how <li> has a key attribute. For each item in a list, you should pass a string or a number that uniquely identifies that item among its siblings. Usually, a key should be coming from your data, such as a database ID. React uses your keys to know what happened if you later insert, delete, or reorder the items.

Responding to events

You can respond to events by declaring event handler functions inside your components:

Notice how onClick={handleClick} has no parentheses at the end! Do not call the event handler function: you only need to pass it down . React will call your event handler when the user clicks the button.

Updating the screen

Often, you’ll want your component to “remember” some information and display it. For example, maybe you want to count the number of times a button is clicked. To do this, add state to your component.

First, import useState from React:

Now you can declare a state variable inside your component:

You’ll get two things from useState : the current state ( count ), and the function that lets you update it ( setCount ). You can give them any names, but the convention is to write [something, setSomething] .

The first time the button is displayed, count will be 0 because you passed 0 to useState() . When you want to change state, call setCount() and pass the new value to it. Clicking this button will increment the counter:

React will call your component function again. This time, count will be 1 . Then it will be 2 . And so on.

If you render the same component multiple times, each will get its own state. Click each button separately:

Notice how each button “remembers” its own count state and doesn’t affect other buttons.

Using Hooks

Functions starting with use are called Hooks . useState is a built-in Hook provided by React. You can find other built-in Hooks in the API reference. You can also write your own Hooks by combining the existing ones.

Hooks are more restrictive than other functions. You can only call Hooks at the top of your components (or other Hooks). If you want to use useState in a condition or a loop, extract a new component and put it there.

Sharing data between components

In the previous example, each MyButton had its own independent count , and when each button was clicked, only the count for the button clicked changed:

Diagram showing a tree of three components, one parent labeled MyApp and two children labeled MyButton. Both MyButton components contain a count with value zero.

Initially, each MyButton ’s count state is 0

The same diagram as the previous, with the count of the first child MyButton component highlighted indicating a click with the count value incremented to one. The second MyButton component still contains value zero.

The first MyButton updates its count to 1

However, often you’ll need components to share data and always update together .

To make both MyButton components display the same count and update together, you need to move the state from the individual buttons “upwards” to the closest component containing all of them.

In this example, it is MyApp :

Diagram showing a tree of three components, one parent labeled MyApp and two children labeled MyButton. MyApp contains a count value of zero which is passed down to both of the MyButton components, which also show value zero.

Initially, MyApp ’s count state is 0 and is passed down to both children

The same diagram as the previous, with the count of the parent MyApp component highlighted indicating a click with the value incremented to one. The flow to both of the children MyButton components is also highlighted, and the count value in each child is set to one indicating the value was passed down.

On click, MyApp updates its count state to 1 and passes it down to both children

Now when you click either button, the count in MyApp will change, which will change both of the counts in MyButton . Here’s how you can express this in code.

First, move the state up from MyButton into MyApp :

Then, pass the state down from MyApp to each MyButton , together with the shared click handler. You can pass information to MyButton using the JSX curly braces, just like you previously did with built-in tags like <img> :

The information you pass down like this is called props . Now the MyApp component contains the count state and the handleClick event handler, and passes both of them down as props to each of the buttons.

Finally, change MyButton to read the props you have passed from its parent component:

When you click the button, the onClick handler fires. Each button’s onClick prop was set to the handleClick function inside MyApp , so the code inside of it runs. That code calls setCount(count + 1) , incrementing the count state variable. The new count value is passed as a prop to each button, so they all show the new value. This is called “lifting state up”. By moving state up, you’ve shared it between components.

By now, you know the basics of how to write React code!

Check out the Tutorial to put them into practice and build your first mini-app with React.

How do you like these docs?

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

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

ConfigProvider 的 theme.components 超过一定数量的组件开启算法,会导致 flatternToken 内递归的 str 字符串长度超过浏览器限制(2^29)从而导致页面崩溃 #48386

@MadCcc

ifmos commented Apr 10, 2024

The text was updated successfully, but these errors were encountered:

@stackblitz

stackblitz bot commented Apr 10, 2024

Sorry, something went wrong.

@github-actions

No branches or pull requests

@zombieJ

IMAGES

  1. React JavaScript Assignment #1 Solution

    assignment 1 react components

  2. Components in React. Components are the heart of any React…

    assignment 1 react components

  3. What Is Components In React Js

    assignment 1 react components

  4. React Components

    assignment 1 react components

  5. React-Assignment-1

    assignment 1 react components

  6. React Components

    assignment 1 react components

VIDEO

  1. React JS Tutorial For Beginners : Part 7 Functional Components In React

  2. assignment 6 video

  3. Code challenge: constructor method

  4. Introduction to React Elements

  5. Frontend Development Using React: Destructuring Assignment

  6. ASSIGNMENT 1

COMMENTS

  1. OlhaHolovina/react-components-assignment-1

    It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes. Your app is ready to be deployed!

  2. Your First Component

    Step 1: Export the component. The export default prefix is a standard JavaScript syntax (not specific to React). It lets you mark the main function in a file so that you can later import it from other files. (More on importing in Importing and Exporting Components !)

  3. Understanding destructive assignment of a component in Reactjs

    1. {component: Component} is indeed destructuring assignment, also called "argument unpacking" in the context of function arguments. It simply gives the prop component a new name Component in the scope of this function. JSX syntax requires all user defined components to be capitalized. ( <component /> will not work.

  4. njbbaer/udemy-react-assignment-1

    Assignment 1. React The Complete Guide. Solution by Nate Baer. Requirements. Create TWO new components: UserInput and UserOutput; UserInput should hold an input element, UserOutput two paragraphs; Output multiple UserOutput components in the App component (any paragraph texts of your choice)

  5. Simplify your React Components with ES6 Object Assignment ...

    Image 1 — Render function for top-level App component in note-taking app. Whilst using Redux or Hooks would be one way to simplify how we use state and props in React, I started to think there ...

  6. Describing the UI

    React is a JavaScript library for rendering user interfaces (UI). UI is built from small units like buttons, text, and images. React lets you combine them into reusable, nestable components. From web sites to phone apps, everything on the screen can be broken down into components. In this chapter, you'll learn to create, customize, and ...

  7. Using destructuring assignment in React

    When using destructuring assignment, you can reduce that long syntax and make it better. First, destructure the userData props before passing it to the component: const { auth, user} = userData. Then pass it into the component as two props: <Profile auth={auth} user={user}>.

  8. Passing Props to a Component

    Try replacing the <Avatar> inside <Card> with some text to see how the Card component can wrap any nested content. It doesn't need to "know" what's being rendered inside of it. You will see this flexible pattern in many places. You can think of a component with a children prop as having a "hole" that can be "filled in" by its parent components with arbitrary JSX.

  9. Make a New Component :: Introduction to Web Dev

    Make a New Component. With your application set up, you are ready to make your first component. ... React, Part 1. Reading. Introduction; React Components; Create a React Application; More on Vite; ... Assignment 1: Candidate Testing. Project Introduction; Part 1: Minimum Viable Quiz;

  10. Component

    componentDidMount() If you define the componentDidMount method, React will call it when your component is added (mounted) to the screen. This is a common place to start data fetching, set up subscriptions, or manipulate the DOM nodes. If you implement componentDidMount, you usually need to implement other lifecycle methods to avoid bugs.For example, if componentDidMount reads some state or ...

  11. GitHub

    Saved searches Use saved searches to filter your results more quickly

  12. GitHub

    The assignment was defined by our instructor as follows: Create TWO new components: UserInput and UserOutput. UserInput should hold an input element, UserOutput two paragraphs. Output multiple UserOutput components in the App component (any paragraph texts of your choice)

  13. Solution for Assignment 1: Time to Practice: React & Component Basics

    Solution for Assignment 1: Time to Practice: React & Component Basics, "React - The Complete Guide (incl Hooks, React Router, Redux)" by Maximilian Schwarzmüller - MMuratti/Expenses

  14. React Exercises

    We have gathered a variety of React exercises (with answers) for each React Chapter. Try to solve an exercise by filling in the missing parts of a code. If you're stuck, hit the "Show Answer" button to see what you've done wrong. Count Your Score. You will get 1 point for each correct answer. Your score and total score will always be displayed.

  15. Part 1: Naming Conventions

    React Best Practices in 2023 (4 Part Series) 1 Part 1: Naming Conventions - The Foundation of Clean Code 2 Part 2: Folder Structure - Building a Solid Foundation 3 Part 3: Component Structure - Building Reusable and Maintainable Components in React! 4 Part 4: Writing Clean and Efficient React Code- Best Practices and Optimization Techniques ...

  16. Quick Start

    For example, maybe you want to count the number of times a button is clicked. To do this, add state to your component. First, import useState from React: import { useState } from 'react'; Now you can declare a state variable inside your component: function MyButton() {. const [count, setCount] = useState(0);

  17. ssgarx/React-Assignment-1---Rendering-Multiple-Components-with-React

    Contribute to ssgarx/React-Assignment-1---Rendering-Multiple-Components-with-React development by creating an account on GitHub.

  18. Prop destructuring inside of react state

    The only to keep it inside of the class property is to use a getter (which will be invoked at the first render): state = {. get animation() {. const { active } = this.props; return active ? 1 : 0;

  19. GitHub

    Note: this is a one-way operation. Once you eject, you can't go back!. If you aren't satisfied with the build tool and configuration choices, you can eject at any time. This command will remove the single build dependency from your project.

  20. reactjs

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams Create a free Team

  21. ConfigProvider 的 theme.components 超过一定数量的 ...

    页面崩溃 Environment Info antd 5.16.1 React 18.2.0 System macOS Monterey 12.3.1 Browser Microsoft Edge 123..2420.81 (正式版本) (x86_64) ... ConfigProvider 的 theme.components 超过一定数量的组件开启算法,会导致 flatternToken 内递归的 str 字符串长度超过浏览器限制 ...