assigning a MUI component in a variable, and using it later, in React

Viewed 195

I want to store an MUI component, more specifically an MUI icon, in a variable, something like

item.icon = <FilterListIcon />;

And later, in other components, doing:

<ListItem button key={item.text} onClick={item.onClick}>
    {item.icon &&
        {
            <ListItemIcon>{item.icon}</ListItemIcon> 
        }}
    <ListItemText primary={item.text} />
</ListItem>

But, when I do so, the browser page gets empty, everything disappears

I'm doing the same with the name and other stuff, but it works:

item.text = 'Item 1 for spv';
item.onClick = () => navigate('/showPlainVideos');

How could I fix this?

1 Answers

I guess you are looking for something like this:

import Button from "@mui/material/Button";

export default function App() {
  const someInstances = [
    <Button variant="contained">Hello World</Button>,
    <Button variant="contained">Hello1 World</Button>,
    <Button variant="contained">Hello2 World</Button>
  ];

  return (
    <div>
      <div>{someInstances}</div>
      {/*do some processing if you want*/}
      <div>{someInstances.map((ins) => ins)}</div>
    </div>
  );
}

codesandbox.io: https://codesandbox.io/s/intelligent-flower-v1dsy?file=/src/App.js:0-437

Related