Data within object not recognized by TableCell Material UI element

I am currently facing an issue where the content of an object is not being displayed within the Material UI component TableCell.

Interestingly, I have used the same approach with the Title component and it shows the content without any problems.

function RecordContent({ repos, selected }) {
  var language = {}
  switch (selected) {
    case "EU":
      selected = "EU";
      language  = repos[0].terms;
      break;
    case "ES":
      selected = "ES";
      language = repos[1].terms;
      break;
    case "EN":
      selected = "EN";
      language = repos[2].terms;
      break;
  }

  const [open, setOpen] = React.useState(true);
  const toggleDrawer = () => {
    setOpen(!open);
  };

  return (
    <ThemeProvider theme={mdTheme}>
      <Box sx={{ display: 'flex' }}>
        <Box
          component="main"
          sx={{
            backgroundColor: (theme) =>
              theme.palette.mode === 'light'
                ? theme.palette.grey[100]
                : theme.palette.grey[900],
            flexGrow: 1,
            height: '100vh',
            overflow: 'auto',
          }}
        >
          <Toolbar />
          <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
            <Grid container spacing={3}>
              {/* Recent Orders */}
              <Grid item xs={12}>
                <Paper sx={{ p: 2, display: 'flex', flexDirection: 'column' }}>
                  {/*It shows the content*/}
                  <Title>{language.record}</Title>
                  <Table size="small">
                    <TableHead>
                        <TableRow>
                          {/*It won't show the content*/}
                          <TableCell>{language.subject}</TableCell>
                          <TableCell>Year</TableCell>
                          <TableCell>{language.group}</TableCell>
                          <TableCell>{language.type}</TableCell>
                          <TableCell>{language.credits}</TableCell>
                          <TableCell>{language.grade}</TableCell>
                          <TableCell>{language.qualificationdate}</TableCell>
                          <TableCell align="right">{language.call}</TableCell>
                        </TableRow>
                    </TableHead>
                    <TableBody>
                      {rows.map((row) => (
                        <TableRow key={row.id}>
                          <TableCell>{row.subject}</TableCell>
                          <TableCell>{row.year}</TableCell>
                          <TableCell>{row.group}</TableCell>
                          <TableCell>{row.type}</TableCell>
                          <TableCell>{row.credits}</TableCell>
                          <TableCell>{row.grade}</TableCell>
                          <TableCell>{row.qualificationdate}</TableCell>
                          <TableCell align="right">{row.call}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
{/*                  <Link color="primary" href="#" onClick={preventDefault} sx={{ mt: 3 }}>
                    See more orders
                  </Link>*/}
                </Paper>
              </Grid>
            </Grid>
          </Container>
        </Box>
      </Box>
    </ThemeProvider>
  );
}

export default class Record extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      selectedLanguage: 'EU',
      repos: null,
      error: null
    }

  }

  render() {
    const { selectedLanguage, repos, error } = this.props

    return (
      <React.Fragment>
          {repos && <RecordContent repos={repos} selected={selectedLanguage} />}
      </React.Fragment>
    )
  }
}

To help visualize the issue, a screenshot is provided for reference.

https://i.stack.imgur.com/TkjXg.png

Despite successfully including objects in other Material UI and HTML components previously, there seems to be an issue specifically with TableCell. No errors are showing up in the console either.

Answer №1

If you want to achieve this in the best possible way, you should assign the language to a state variable and update it within the useEffect based on the value of selected:

const [language, setLanguage] = useState({})
useEffect(() => {
  switch (selected) {
    case "EU":
      setLanguage(repos[0].terms)
      break;
    case "ES":
      setLanguage(repos[1].terms)
      break;
    case "EN":
      setLanguage(repos[2].terms)
      break;
    default:
      setLanguage({})
  }
}, [selected])

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

if a condition is not being properly assessed

Currently, I am working on a $.ajax call to retrieve data in JSON format. Within this JSON data, there is an element called "status." My code snippet checks if the value of `data.status` is equal to "success" and performs some actions accordingly. Despite ...

Having trouble with the clear button for text input in Javascript when using Bootstrap and adding custom CSS. Any suggestions on how to fix

My code was working perfectly until I decided to add some CSS to it. You can view the code snippet by clicking on this link (I couldn't include it here due to issues with the code editor): View Gist code snippet here The code is based on Bootstrap. ...

Understanding the scope of variables in a JavaScript callback function

I am attempting to send an object variable to a callback function const sql = require('mssql'); const asset_update = function (connection, addr) { this.connection = connection; this.addr = addr; this.addr_long = parseInt(addr, 16); } ...

The loading component is displayed at the top of the page

In my project, I added a loading screen feature using a loader component in the _app.js file. function MyApp({ Component, pageProps }) { const [loading, setLoading] = useState(false) Router.events.on('routeChangeStart', (url) => { setLo ...

Issue: unable to inject ngAnimate due to uncaught object error

Whenever I attempt to inject 'ngAnimate' into my app, I encounter issues with instantiation. Here is the code snippet in question: var app = angular.module('musicsa', [ 'ngCookies', 'ngResource', 'ngSanit ...

Which is the better option: utilizing the submit event of the form, or incorporating ajax functionality?

Forms are an essential part of my website design, and I often find myself contemplating whether it's better to submit a form using a standard submit button or utilizing Ajax. Typically, I opt for Ajax to prevent the dreaded issue of form re-submission ...

The resolution of Q.all does not occur in the expected order

I'm currently facing an issue with the order in which promises are being executed in Node.js. The goal of the code is as follows: a) Run a query and use the resulting latitude/longitude pairs to b) Calculate the shortest paths (using an async funct ...

The gradual disappearance and reappearance of a table row

I am struggling with making a row fade out when a specific select value is chosen (such as "termination"), and fade in when any other option is selected. The code works perfectly fine when the div ID is placed outside the table, but once I encapsulate it w ...

Adjust the size of the child div to fit the remaining space within the parent div

I'm dealing with a situation where there are two child divs inside a parent div. The first child div takes up 32% of the width, while the second child div takes up 68% of the width. If I were to set the display of the first child div to "none", how ca ...

Select one href by clicking and apply addClass

I have a one-page HTML document with links in the header. I want to make it so that when I click on a link (<a>), only that specific link changes its class to (.links). I've tried various methods, but the current jQuery method I'm using ad ...

Issues encountered when attempting to append the array objects to HTML using $.getjson

Hello, I have a JSON data structure as shown below: [{ "menu": "File", }, { "menu": "File1", }] I have created jQuery code to dynamically add the response to my HTML page like this: $(document).ready(function () { $.getJSON('data.json&a ...

Utilizing Next.js to create a Higher Order Component (HOC) for fetching data from a REST API using Typescript is proving to be a challenge, as the

In my withUser.tsx file, I have implemented a higher order component that wraps authenticated pages. This HOC ensures that only users with a specified user role have access to the intended pages. import axios, { AxiosError } from "axios"; import ...

If a particular <td> element is present on the page, exhibit a unique <div>

I have a webpage with various HTML elements. <div class="alert">Your message was not sent.</div> <p class="pending">Email Pending</p> I would like to display the div.alert only if the p.pending is present. Is ...

Is it considered poor form for an Angular controller to invoke a function on a directive?

My custom Angular directive functions as a unique combobox, where clicking on the input control reveals a div below it with a list of items from a model object. The user can type text into the input control to filter the displayed list. In addition to the ...

How can you retrieve command line variables within your code by utilizing npm script in webpack?

I'm trying to access command line parameters from an npm script in my "constants.js" file. While I have been able to access parameters in the webpack.config.js file using process.env, it seems to be undefined in my app source files. The scenario con ...

Tips for sharing data between routes in Next.js App router

Currently using App router and in need to transfer parameters as an object without reliance on useParams & useSearchParams Suppose there is an object named person const person: Person = { name: "John Doe", age: 25, address: "123 M ...

What kind of Antd type should be used for the form's onFinish event?

Currently, I find myself including the following code snippet repeatedly throughout my project: // eslint-disable-next-line @typescript-eslint/no-explicit-any const handleCreate = (input: any): void => { saveToBackend({ title: input.title, oth ...

What is the process for selecting dependencies in react native?

Expanding on this: Imagine I have a React Native project running on a specific version with various npm packages installed. Each npm package will have its own node_modules and build.gradle file. In what situations will the dependencies local to that packag ...

How to change router.push in NextJS to navigate to non-shallow routes

On my search page, I encounter a problem when users make consecutive searches without refreshing the page. Even though the query in the URL updates, the products on the page remain unchanged. I attempted to solve this by using router.push("/search-pa ...

An issue encountered with res.download() following res.render() in Node.js

Just started working with Node JS and ran into an issue: Error: Can't set headers after they are sent. I've checked my code, and the problem seems to be related to res.download(); Is there a way to display the view without using res.render()? ...