Looking for guidance on understanding how deconstructing props works in my specific situation within React

Currently, I am enrolled in the fullstackopen2021 program offered by Helsinki University.

As a novice developer, I am focusing on understanding destructuring, which seems a bit complex to me at this stage.

The structure of my <App/> component is as follows:

const App = () => {
    const course = 'Half stack application development',
        parts = [

            {
                name: 'Fundamentals of React',
                exercises: 10,
            },
            {
                name: 'Using props to pass data',
                exercises: 7,
            },
            {
                name: 'State of a  component',
                exercises: 14,
            }
        ];

    return (
        <>
            <table>
                <Header course={course} />
                <Content parts={parts} />
                <Total parts={parts} />
            </table>
        </>
    )
}

This is how my <Content/> component looks like:

const Content = ({ parts: [part1, part2, part3] }) => {
    // console.log(part1, part3, part2);
    return (
        <>
            <thead>
                <tr>
                    <th>Course Content</th>
                    <th>Exercises</th>
                </tr>
            </thead>
            <tbody>
                <Part part={part1} />
                <Part part={part2} />
                <Part part={part3} />
            </tbody>
        </>
    )
}

Lastly, here is my <Part/> component's structure:

const Part = ({ part: { name, exercises } }) => {
    return (
        <>
            <tr>
                <th scope={"row"}>{name}</th>
                <td align={"right"}>{exercises}</td>
            </tr>
        </>
    )
}

I have successfully implemented destructuring in the <Content/> component. However, when I try using curly braces instead like this:

const Content = ({ parts: {part1, part2, part3} }) => {
    //same as above
}

By employing {} curly brackets as shown in { parts: {part1, part2, part3}, it causes the application to malfunction. I am perplexed as to why this method fails while the initial implementation succeeds. Can anyone explain why this approach is incorrect and why the former one works?

Answer №1

When destructuring a property from an object, remember to use curly braces. If you are destructuring elements from an array, make sure to use brackets.

For example:

const obj = { name: 'me' }
const { name } = obj
console.log(name)

const arr = [1, 2, 3]
const [one, two, three] = arr
console.log(one, two, three)

In some cases, you may need to combine both techniques:

const obj = { arr: [1, 2, 3] }
// First destructure 'arr', then use brackets to destructure the elements by their indexes
const { arr: [one, two, three] } = obj
console.log(one, two, three)

You can also apply this method to nested properties:

const obj = { firstLevel: { secondLevel: { name: 'me' } } }
const { firstLevel: { secondLevel: { name } } } = obj
console.log(name)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving information from the API to populate a child component in Next.js

I have been developing a header component and here's the code snippet: import style from '../../styles/header.css'; import '../../styles/globals.css'; export default function Header({data}){ const [showMe, setShowMe] = useStat ...

Set the current value of the chosen option in a group of dropdown menus

In my project, I have a primary <FirstStep /> module that includes two dropdown components. The main goal is to establish the state of the selected values in these dropdowns. The issue arises when dealing with multiple dropdowns because it's no ...

Is it possible to leverage the className attribute in Material UI components?

Currently using React alongside Material-UI(MUI) for the frontend development. Encountering an issue with the Button Component in MUI, specifically the className prop. Struggling to apply custom styles using classes defined in the style.css file. Conside ...

What are some techniques for testing masked input fields?

Looking for guidance on unit testing a masked input field in React using react-testing-library? The component is built with Material UI and React Hook Form. I've included some code and examples to help you out. Thank you in advance! Test file: let ...

What steps can I take to limit access to my API exclusively for the Frontend?

I'm in the process of creating a gaming platform, and unfortunately, there has been an exploitation of the API. How can I establish a set of "approved domains" that are allowed to access my API? The previous misuse of the API resulted in individuals ...

React: Material UI causing an error due to an invalid hook call

Working on a React project using create-react-app with material UI, encountering errors like: https://i.stack.imgur.com/mhjkE.png Appears to be an internal issue with material UI once setting a custom theme. import { ThemeProvider } from "@mui/material/ ...

Highlighting the content within Material-UI's <Dialog> using ReactJS without affecting the entire webpage

I have an issue in my ReactJS project with the <Dialog> component from Material-UI (http://www.material-ui.com/#/components/dialog). When I open the <Dialog> and press command + a on my Mac, it highlights the entire page instead of just the con ...

Guide on customizing the error color and underline color when input is focused in material-ui v1.0.0-beta.40

Currently implementing Material-UI v1.0.0-beta.40 and aiming to customize the border color and error text color. Any suggestions on how to achieve this? ...

Using @emotion/styled alongside esbuild has caused an issue where importing styled11 as default.div is not functioning as expected

Working on building a website using esbuild, react, and emotion/MUI has been smooth sailing so far. However, I've hit a roadblock with getting the styled component from @emotion/styled to function properly. uncaught TypeError: import_styled11.default ...

Creating a generic component map resolver for flexible applications

Currently, I am engaged in a project where the backend allows for the modeling of dynamic content that is later displayed as Components on the frontend. Everything seems to be functioning well, except when dealing with models where the dynamic content con ...

Creating a redux store with an object using typescript: A step-by-step guide

Having recently started using Redux and Typescript, I'm encountering an error where the store is refusing to accept the reducer when working with objects. let store = createStore(counter); //error on counter Could this be due to an incorrect type set ...

We're sorry, but the module you are looking for cannot be found. An error has occurred while trying

Struggling with an error while using React Material-UI to design my interface. The issue arises when using a specific component in the main layout. Seeking assistance from anyone who can help me find a solution. [287] ./src/components/RadioCustom.js 5.42 ...

Implementing Placeholder Text Across Multiple Lines with Material UI

Currently, for the React App I am developing, I am utilizing Material UI. In order to achieve a multi-line placeholder for a textarea using the TextField component, here is what I have so far: <TextField id="details" ful ...

Unlimited API requests triggered by state changes within a callback

I am attempting to fetch data from an API and display it in a treeview using Material-UI. When the data is static, everything works perfectly fine. However, when I use the API in a callback function, it triggers an endless loop of calls... const getTreeIte ...

proper integration of socket.io

I have been experimenting with socket io for my project to display online friends, and I have noticed an issue that seems strange to me. Every time the page is rerendered (whether due to a user changing their profile information or sending a friend request ...

Transform routeParams from string to numerical format

Currently, I am working on a straightforward project where I need to retrieve data based on the id number using "routeParams". However, I encountered an issue because the "routeParams" is in string format and I actually need it to be converted to a numbe ...

Troubles encountered with adapting apexcharts size within a react environment

As a novice front-end coder transitioning from a data analyst background, I am currently facing an issue with integrating an ApexChart visual into a flexbox element. The visual appears fine at a resolution of 2560x1440 pixels. However, upon further resizin ...

What is the best way to design custom Tabs with multiple labels within each tab using material UI?

I am utilizing material UI with the material-ui/Tabs component. Here is a code snippet... import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import AppBar from &apo ...

Displaying tooltips dynamically for newly added elements all sharing a common class in React

I'm facing an issue with the primereact tooltip component from . Everything seems to be working fine except for the target property. When I have multiple elements on a page with the same class, the tooltip works as expected. However, when I add a new ...

Data vanishing in upcoming authentication session in test environment

I have encountered an issue with next auth in my next.js project. During development, the session data is lost if the server refreshes or if I switch to another tab and return to it. This forces me to sign out and then sign back in to restore the session d ...