React complaining about key-less children when all children have keys - reactjs

As the title says, React is throwing an error about children in a list having unique keys and I have no clue why. I am building a Twitch chat clone, and this is happening with my emote picker, where every emote available for your use is listed as a clickable icon. Every map function I use spits out components with keys. I even went through every single component and added a unique key whether it really needed it or not, and I am still getting the warning. Clicking the first few trace links leads to nothing useful.
I know my code might not be super clear, and I apologize for this, but any help would be appreciated.
Here is the return statement for the affected component:
return (
<Popover placement="top">
<PopoverTrigger>
<Button disabled={!loggedIn || !connected}>
{
<Box
as="img"
width={[12, 10, 10, 8]}
alt="Emote Picker"
// src="https://static-cdn.jtvnw.net/emoticons/v2/305954156/static/light/3.0" // PogChamp
src="https://static-cdn.jtvnw.net/emoticons/v2/307445021/static/light/3.0" // Orangie
title="Emote Picker"
/>
}
</Button>
</PopoverTrigger>
<PopoverContent>
<PopoverArrow />
<PopoverCloseButton />
<Flex height={400} overflow="auto" direction="column">
{showBTTVChannel && (
<>
<PopoverHeader>BTTV Channel Emotes</PopoverHeader>
<PopoverBody>
<Flex flexWrap="wrap">
{bttvEmotes !== null &&
// eslint-disable-next-line array-callback-return
Object.keys(bttvEmotes).map((key, index) => {
if (bttvEmotes[key]['category'] === 'bttv_channel') {
return (
<ChatEmote
key={index}
name={key}
src={
bttvEmotes[key][userOptions.emoteQuality + 'x']
}
height={8}
margin={1.5}
onClick={() => onClickHandler(key)}
/>
);
}
})}
</Flex>
</PopoverBody>
</>
)}
{showFFZChannel && (
<>
<PopoverHeader>FFZ Channel Emotes</PopoverHeader>
<PopoverBody>
<Flex flexWrap="wrap">
{bttvEmotes !== null &&
// eslint-disable-next-line array-callback-return
Object.keys(bttvEmotes).map((key, index) => {
if (bttvEmotes[key]['category'] === 'ffz_channel') {
return (
<ChatEmote
key={index}
name={key}
src={
bttvEmotes[key][userOptions.emoteQuality + 'x']
}
height={8}
margin={1.5}
onClick={() => onClickHandler(key)}
/>
);
}
})}
</Flex>
</PopoverBody>
</>
)}
{showBTTVShared && (
<>
<PopoverHeader>BTTV Shared Emotes</PopoverHeader>
<PopoverBody>
<Flex flexWrap="wrap">
{bttvEmotes !== null &&
// eslint-disable-next-line array-callback-return
Object.keys(bttvEmotes).map((key, index) => {
if (bttvEmotes[key]['category'] === 'bttv_shared') {
return (
<ChatEmote
key={index}
name={key}
src={
bttvEmotes[key][userOptions.emoteQuality + 'x']
}
height={8}
margin={1.5}
onClick={() => onClickHandler(key)}
/>
);
}
})}
</Flex>
</PopoverBody>
</>
)}
{showEmotes &&
// eslint-disable-next-line array-callback-return
Object.keys(emoteSets.current).map(key => {
if (key !== 'Twitch Global') {
return (
<>
<PopoverHeader>{key}</PopoverHeader>
<PopoverBody>
<Flex flexWrap="wrap">
{emoteSets.current !== null &&
Object.keys(emoteSets.current[key]['emotes']).map(
(key, index) => {
return (
<ChatEmote
key={index}
name={key}
src={
userEmotes[key][
userOptions.emoteQuality + 'x'
]
}
height={8}
margin={1.5}
onClick={() => onClickHandler(key)}
/>
);
}
)}
</Flex>
</PopoverBody>
</>
);
}
})}
<PopoverHeader>BTTV Global Emotes</PopoverHeader>
<PopoverBody>
<Flex flexWrap="wrap">
{bttvEmotes !== null &&
// eslint-disable-next-line array-callback-return
Object.keys(bttvEmotes).map((key, index) => {
if (bttvEmotes[key]['category'] === 'bttv_global') {
return (
<ChatEmote
key={index}
name={key}
src={bttvEmotes[key][userOptions.emoteQuality + 'x']}
height={8}
margin={1.5}
onClick={() => onClickHandler(key)}
/>
);
}
})}
</Flex>
</PopoverBody>
{showEmotes && (
<>
<PopoverHeader>Twitch Global</PopoverHeader>
<PopoverBody>
<Flex flexWrap="wrap">
{emoteSets.current !== null &&
Object.keys(
emoteSets.current['Twitch Global']['emotes']
).map((key, index) => {
return (
<ChatEmote
key={index}
name={key}
src={userEmotes[key][userOptions.emoteQuality + 'x']}
height={8}
margin={1.5}
onClick={() => onClickHandler(key)}
/>
);
})}
</Flex>
</PopoverBody>
</>
)}
</Flex>
</PopoverContent>
</Popover>
);

key must added to the parent wrapper component which you're returning
key is missing -->
{showEmotes &&
// eslint-disable-next-line array-callback-return
//map second argument return the index of current element
Object.keys(emoteSets.current).map((key,i) => {
if (key !== 'Twitch Global') {
return (
//missing key
<div key={i}>
<PopoverHeader>{key}</PopoverHeader>
<PopoverBody>
<Flex flexWrap="wrap">
{emoteSets.current !== null &&
Object.keys(emoteSets.current[key]['emotes']).map(
(key, index) => {
return (
<ChatEmote
key={index}
name={key}
src={
userEmotes[key][
userOptions.emoteQuality + 'x'
]
}
height={8}
margin={1.5}
onClick={() => onClickHandler(key)}
/>
);
}
)}
</Flex>
</PopoverBody>
</>
does this solve issue ?

Related

How to change from Table to Card in React?

I am rendering the products in a table but I want to display them as card. Every time I touch the code it stops working, I've tried mixing them together but nothing, any suggestions?
function Products(props) {
function Products(products) {
if (products === null) return;
return products.map((product) => (
<ListGroup.Item key={product.Id}>
<Link to={`/products/${product.name}`} key={product.id}> {product.name}
</Link>
</ListGroup.Item>
));
}
return (
<>
<h1>Products</h1>
<Stack direction="horizontal" gap={3}>
<ListGroup className="align-self-start w-75">
<ProductContext.Consumer>
{({ products }) => Products(products)}
</ProductContext.Consumer>
</ListGroup>
<Outlet />
</Stack>
</>
);
}
export default Products;

How can I write if statement inside a map in react?

I am trying to write an if statement if invited is not undefined.
Here is my following code base:
{tabs[activeTab] === "Pending" &&
userInvitedList.map((user, index) => (
{user.invited.pending && ()}
<InviteSentList
user={user}
index={index}
selected={selected}
handleSelect={handleSelect}
/>
))}
How can I check user.invited.pending in this case?
You can do this.
{tabs[activeTab] === "Pending" &&
userInvitedList.map((user, index) => (
{user.invited.pending &&
<InviteSentList
key={index}
user={user}
index={index}
selected={selected}
handleSelect={handleSelect}
/>
}
))}
You can refer more in details here [if condition inside map][1]
[1]: https://stackoverflow.com/questions/44969877/if-condition-inside-of-map-react#:~:text=I%20have%20a%20map(),)%20%3A%20(%20%2F%2F%20ByeBye!%20)%7D
If you want show InviteSentList when user.invited.pending is not undefined, you just update like this:
{user.invited.pending && (
<InviteSentList
user={user}
index={index}
selected={selected}
handleSelect={handleSelect}
key={user.id} // unique
/>
)}
Note: You need to add key props
if you put if statement or something like this in map, you can remove () after arrow function and change with curly brackets {}. You can do this:
{tabs[activeTab] === "Pending" &&
userInvitedList.map((user, index) => {
user.invited.pending && (
<InviteSentList
key={index}
user={user}
index={index}
selected={selected}
handleSelect={handleSelect}
/>
)}
)}
You can do it like this.
{tabs[activeTab] === "Pending" &&
userInvitedList.map((user, index) => {
return user.invited.pending ? (
<InviteSentList
user={user}
index={index}
selected={selected}
handleSelect={handleSelect}
/>
) : null;
})}

Is there a way to take a code which is defined inside render , out from render function in React?

I have coded a function inside render function. When I call it in the return it works. But now what I want to do is get it out and place it before render. Is there a way to do it like that? I have given the function below.In here what I have commented is the final output what I want to get
import React from 'react';
import { Row, Col, Form, FormGroup, Input, Label } from 'reactstrap';
import * as Icon from 'react-bootstrap-icons';
import ReactQuill from 'react-quill';
import ActionButton from '../../components/ActionButton/ActionButton';
import InputFieldWithImage from '../../components/InputFieldWithImage/InputFieldWithImage';
import SelectedFilesDisplayLabel from '../../components/SelectedFilesDisplayLabel/SelectedFilesDisplayLabel';
import DropDown from '../../components/DropDown/DropDown';
import CustomToolbar from '../../components/EditorToolbar/EditorToolbar';
import 'react-quill/dist/quill.snow.css';
import './Popup.scss';
import Amy from './../../assets/images/Amy.png';
const icons = ReactQuill.Quill.import('ui/icons');
icons['link'] = <Icon.Link />;
class AddTicket extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedFile: null,
title: '',
description: '',
assignee: '',
employer: '',
type: 'A',
priority: 'Top',
edit: '',
text: '',
editorHtml: '',
uploadedFileName: '',
uploadedFileType: '',
flagPdf: false,
flagImage: false,
flagDoc: false,
selectedFiles: [],
dropdownOpen: false,
isOpen: false,
typeArray: ['A', 'B', 'C', 'D'],
priorityArray: ['Top', 'Middle', 'Least', 'No']
};
}
// This is the function for file upload.Here it checks whether there is the same file already attached
// and if not stored in selectedFiles array.Flag is used here in the function to keep the state of the file
// whether there contain a file with same name.
handleChangeFile = (event) => {
let fileExists;
let temp = [];
let files = [];
let tempSelectedFilesArr = this.state.selectedFiles;
for (let i = 0; i < event.target.files.length; i++) {
let file = event.target.files[i];
if (
file.type === 'application/pdf' ||
file.type === 'image/png' ||
file.type === 'image/jpeg' ||
file.type === 'application/msword' ||
file.type ===
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
file.type === 'video/mp4'
) {
files.push(file);
}
}
if (tempSelectedFilesArr.length > 0) {
for (let i = 0; i < files.length; i++) {
fileExists = 0;
for (let j = 0; j < tempSelectedFilesArr.length; j++) {
if (files[i].name === tempSelectedFilesArr[j].name) {
fileExists = 1;
break;
}
}
if (fileExists === 0) {
temp.push(files[i]);
}
}
} else {
for (let i = 0; i < files.length; i++) {
temp.push(files[i]);
}
}
this.setState({
selectedFiles: tempSelectedFilesArr.concat(temp)
});
};
// This handles text which input to title,assignee and employee
handleChangeInputs = (event) => {
this.setState({
[event.target.name]: event.target.value
});
};
// In this function, text which are input into the descripion box ,are stored in the state
handleDescription = (html) => {
this.setState({ editorHtml: html });
};
// These two function handleType,handlePriority are send as props to the dropdown component.
handleType = (e) => {
this.setState({ type: e.currentTarget.textContent });
};
handlePriority = (e) => {
this.setState({ priority: e.currentTarget.textContent });
};
// This function handle all the input values. Values are send to the backend from this
handleSubmit = (event) => {
event.preventDefault();
console.log(this.state.title);
console.log(this.state.type);
console.log(this.state.priority);
console.log(this.state.assignee);
console.log(this.state.employer);
this.props.handleClose();
};
// Uploaded files are displayed in the screen. After clicking the close button,
// this function calls
cardClose(value) {
let temp = this.state.selectedFiles.filter((n) => {
return n.name !== value;
});
this.setState({
selectedFiles: temp
});
}
// These are used in the react quill component.
static modules = {
toolbar: {
container: '#toolbar'
}
};
// decription = this.state.selectedFiles.map((item, key) => {
// let size = item.size / 1048576;
// size = size.toFixed(2);
// const K = item.name;
// return (
// <div>
// {item.type === 'application/pdf' && (
// <SelectedFilesDisplayLabel
// onClick={() => {
// this.cardClose(K);
// }}
// name={item.name}
// size={size}
// icon={<Icon.FileEarmarkText />}
// />
// )}
// {item.type === 'image/png' && (
// <SelectedFilesDisplayLabel
// onClick={() => {
// this.cardClose(K);
// }}
// name={item.name}
// size={size}
// icon={<Icon.Image />}
// />
// )}
// {item.type === 'image/jpeg' && (
// <SelectedFilesDisplayLabel
// onClick={() => {
// this.cardClose(K);
// }}
// name={item.name}
// size={size}
// icon={<Icon.Image />}
// />
// )}
// {item.type === 'application/msword' && (
// <SelectedFilesDisplayLabel
// onClick={() => {
// this.cardClose(K);
// }}
// name={item.name}
// size={size}
// icon={<Icon.FileEarmarkText />}
// />
// )}
// {item.type ===
// 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' && (
// <SelectedFilesDisplayLabel
// onClick={() => {
// this.cardClose(K);
// }}
// name={item.name}
// size={size}
// icon={<Icon.FileEarmarkText />}
// />
// )}
// {item.type === 'video/mp4' && (
// <SelectedFilesDisplayLabel
// onClick={() => {
// this.cardClose(K);
// }}
// name={item.name}
// size={size}
// icon={<Icon.Film />}
// />
// )}
// </div>
// );
// });
render() {
let fileUploader = React.createRef();
const decription = this.state.selectedFiles.map((item, key) => {
let size = item.size / 1048576;
size = size.toFixed(2);
const K = item.name;
return (
<div>
{item.type === 'application/pdf' && (
<SelectedFilesDisplayLabel
onClick={() => {
this.cardClose(K);
}}
name={item.name}
size={size}
icon={<Icon.FileEarmarkText />}
/>
)}
{item.type === 'image/png' && (
<SelectedFilesDisplayLabel
onClick={() => {
this.cardClose(K);
}}
name={item.name}
size={size}
icon={<Icon.Image />}
/>
)}
{item.type === 'image/jpeg' && (
<SelectedFilesDisplayLabel
onClick={() => {
this.cardClose(K);
}}
name={item.name}
size={size}
icon={<Icon.Image />}
/>
)}
{item.type === 'application/msword' && (
<SelectedFilesDisplayLabel
onClick={() => {
this.cardClose(K);
}}
name={item.name}
size={size}
icon={<Icon.FileEarmarkText />}
/>
)}
{item.type ===
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' && (
<SelectedFilesDisplayLabel
onClick={() => {
this.cardClose(K);
}}
name={item.name}
size={size}
icon={<Icon.FileEarmarkText />}
/>
)}
{item.type === 'video/mp4' && (
<SelectedFilesDisplayLabel
onClick={() => {
this.cardClose(K);
}}
name={item.name}
size={size}
icon={<Icon.Film />}
/>
)}
</div>
);
});
return (
<div className="popup-box">
<div className="box">
<Form onSubmit={this.handleSubmit} className="form">
{' '}
<div className="form-close-icon">
<Icon.X />
</div>
<Row className="form-row">
<Col xs={11}>
<h1 className="heading">Add new ticket </h1>
</Col>
<Col xs={1} onClick={this.props.handleClose}></Col>
</Row>
<FormGroup>
<Row className="title">
<Col xs={2} className="title-align-one">
<h4>Title</h4>
</Col>
<Col xs={4}>
<Input
type="text"
name="title"
id="title"
value={this.state.title}
onChange={this.handleChangeInputs}
className="input-field"
placeholder="Title of the ticket"
/>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row className="title">
<Col xs={2} className="title-align-two">
<h4>Description</h4>
</Col>
<Col xs={9}>
<div>
<div className="text-box">
<div className="editor-wrapper">
<div className="editor-container">
<div className="text-editor">
<ReactQuill
value={this.state.editorHtml}
onChange={this.handleDescription}
placeholder={this.props.placeholder}
modules={AddTicket.modules}
formats={AddTicket.formats}
/>
<div className="display-cards">{decription}</div>
<div id="toolbar">
<CustomToolbar onInput={this.handleChangeFile} />
</div>
</div>
</div>
</div>
</div>
</div>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row className="title-type">
<Col xs={2} className="title-align-two">
<h4>Type </h4>
</Col>
<Col xs={10}>
<DropDown
onClick={this.handleType}
dropDwonItemArray={this.state.typeArray}
text={this.state.type}
/>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row className="title">
<Col xs={2} className="title-align-two">
<h4>Priority </h4>
</Col>
<Col xs={10}>
<DropDown
onClick={this.handlePriority}
dropDwonItemArray={this.state.priorityArray}
text={this.state.priority}
/>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row className="title">
<Col sm={2} className="title-align-one">
<h4>Assignee</h4>
</Col>
<Col sm={4} className="imageAssigneeCol">
<InputFieldWithImage
value={this.state.assignee}
onChange={this.handleChangeInputs}
picture={Amy}
className="field-image"
/>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row className="title">
<Col xs={2} className="title-align-one">
<h4 className="title-employer">Employer</h4>
<Label className="text-optional">Optional</Label>
</Col>
<Col xs={4}>
<Input
type="text"
name="employer"
id="employer"
value={this.state.employer}
onChange={this.handleChangeInputs}
className="input-field-employee"
/>
</Col>
</Row>
</FormGroup>
<FormGroup>
<Row>
<Col xs={4} className="submit-button">
<ActionButton text="Send" />
</Col>
</Row>
</FormGroup>
</Form>
</div>
</div>
);
}
}
export default AddTicket;
This is how i use it in the return function
<div className="display-cards">{decription}</div>
You can define decription before render() function as below..
decription = () => (
<>
{
// Start .map function
this.state.selectedFiles.map((item, key) => {
let size = item.size / 1048576;
size = size.toFixed(2);
const K = item.name;
return (
<div>
{item.type === 'application/pdf' && (
<SelectedFilesDisplayLabel
onClick={() => {
this.cardClose(K);
}}
name={item.name}
size={size}
icon={<Icon.FileEarmarkText />}
/>
)}
{item.type === 'image/png' && (
<SelectedFilesDisplayLabel
onClick={() => {
this.cardClose(K);
}}
name={item.name}
size={size}
icon={<Icon.Image />}
/>
)}
{item.type === 'image/jpeg' && (
<SelectedFilesDisplayLabel
onClick={() => {
this.cardClose(K);
}}
name={item.name}
size={size}
icon={<Icon.Image />}
/>
)}
{item.type === 'application/msword' && (
<SelectedFilesDisplayLabel
onClick={() => {
this.cardClose(K);
}}
name={item.name}
size={size}
icon={<Icon.FileEarmarkText />}
/>
)}
{item.type ===
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' && (
<SelectedFilesDisplayLabel
onClick={() => {
this.cardClose(K);
}}
name={item.name}
size={size}
icon={<Icon.FileEarmarkText />}
/>
)}
{item.type === 'video/mp4' && (
<SelectedFilesDisplayLabel
onClick={() => {
this.cardClose(K);
}}
name={item.name}
size={size}
icon={<Icon.Film />}
/>
)}
</div>
);
})
// End .map function
}
</>
)
And use it in div of render()
<div className="display-cards">{this.decription()}</div>
Here, you have to know the difference between this.decription and this.decription()
Very important...

Cannot read property map of undefined react

I'm trying to render a component that uses an array of filters to make a list. I pass the array as an argument to the function but it returns an error. The array is not null or undefined because it shows the itens if I log to the console.
Console.log returns:
Here is my code:
const List = (filtrosPorTipo) => {
let filtros = filtrosPorTipo[0]
let valoresDosFiltros = filtrosPorTipo[1]
let lista = (
<List>
{filtros.map((item, index) => {
return (
<>
<ListItem
button
onClick={() => setOpen({ [item]: !open[item] })}
key={item}
>
<ListItemText primary={item} />
{open[item] ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Collapse in={open[item]} timeout='auto'>
<List component='div' disablePadding>
{valoresDosFiltros[index].map((filtro) => {
return (
<>
<ListItem key={filtro}>
<p>{`${filtro}\n`}</p>
<ListItemSecondaryAction>
<Checkbox
label={filtro}
key={filtro.toString()}
color='primary'
onChange={() => handleChecked(filtro)}
checked={checked[filtro]}
/>
</ListItemSecondaryAction>
</ListItem>
<Divider />
</>
)
})}
</List>
</Collapse>
</>
)
})}
</List>
)
return lista
}
Error:
Perhaps the component it's trying to render before "filtros" is assigned. It's a common and logical behavior in React.
Try adding a conditional before the .map() call:
{filtros ? filtros.map((item, index) => {
return (
<>
<ListItem
button
onClick={() => setOpen({ [item]: !open[item] })}
key={item}
>
<ListItemText primary={item} />
{open[item] ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Collapse in={open[item]} timeout='auto'>
<List component='div' disablePadding>
{valoresDosFiltros[index].map((filtro) => {
return (
<>
<ListItem key={filtro}>
<p>{`${filtro}\n`}</p>
<ListItemSecondaryAction>
<Checkbox
label={filtro}
key={filtro.toString()}
color='primary'
onChange={() => handleChecked(filtro)}
checked={checked[filtro]}
/>
</ListItemSecondaryAction>
</ListItem>
<Divider />
</>
)
})}
</List>
</Collapse>
</>
)
}) : null}
You can map over the values when they are present like so. If you are not planning on displaying a Loading screen in the process of waiting for the data then this would work. Otherwise use a ternary operator like the other answer.
{filtros && filtros.map((item, index) => {
return (
<>
<ListItem
button
onClick={() => setOpen({ [item]: !open[item] })}
key={item}
>
<ListItemText primary={item} />
{open[item] ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Collapse in={open[item]} timeout='auto'>
<List component='div' disablePadding>
{valoresDosFiltros[index].map((filtro) => {
return (
<>
<ListItem key={filtro}>
<p>{`${filtro}\n`}</p>
<ListItemSecondaryAction>
<Checkbox
label={filtro}
key={filtro.toString()}
color='primary'
onChange={() => handleChecked(filtro)}
checked={checked[filtro]}
/>
</ListItemSecondaryAction>
</ListItem>
<Divider />
</>
)
})}
</List>
</Collapse>
</>
)
})}
While rendering the component you have to check data in filtrosPorTipo. It has an array value or not. Like below:
const List = (filtrosPorTipo) => {
if (filtrosPorTipo && filtrosPorTipo.length > 0) {
let filtros = filtrosPorTipo[0]
let valoresDosFiltros = filtrosPorTipo[1]
let lista = (
<List>
{filtros.map((item, index) => {
return (
<>
<ListItem
button
onClick={() => setOpen({ [item]: !open[item] })}
key={item}
>
<ListItemText primary={item} />
{open[item] ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Collapse in={open[item]} timeout='auto'>
<List component='div' disablePadding>
{valoresDosFiltros[index].map((filtro) => {
return (
<>
<ListItem key={filtro}>
<p>{`${filtro}\n`}</p>
<ListItemSecondaryAction>
<Checkbox
label={filtro}
key={filtro.toString()}
color='primary'
onChange={() => handleChecked(filtro)}
checked={checked[filtro]}
/>
</ListItemSecondaryAction>
</ListItem>
<Divider />
</>
)
})}
</List>
</Collapse>
</>
)
})}
</List>
)
return lista
}
return 'No data available!'
}

Not apply dynamic class in react js rendering

I am applying class on condition based but it is not apply. But when I apply class name static then it is applied successfully.
const styles = theme => ({
labelsuccess: {
"background-color": "#5cb85c"
},
labelprogress: {
"background-color": "#f0ad4e"
}
});
let labelcolor = [
{
status: "In Progress",
class: "classes.labelprogress"
},
{
status: "Completed",
class: "classes.labelsuccess"
}
];
{Developertasklist.map((task, index) => (
<ListItem key={index} divider="true">
<div className={classes.taskwidth}>
<span className={classes.hideelement}>
{
(foundValue = labelcolor.filter(
obj => obj.status === task.status
)[0].class)
}
</span>
<ListItemText
primary={
<React.Fragment>
{task.name} - {task.due_date}
</React.Fragment>
}
secondary={
<React.Fragment>
<Typography
component="span"
className={foundValue}
color="textPrimary"
>
{task.status}
</Typography>
</React.Fragment>
}
/>
</div>
</ListItem>
))}
Why dynamic class does not apply?
set your variable before the return. Not inside.
with arrow functions, you doesn't need use return if you use brackets like this () => ( ... ), but if you want to set variable or calculating, use with curly brackets and return statement. like this;
() => {
const a = 'variable';
return ( <div class={a}>... );
}
try this one.
{Developertasklist.map((task, index) => {
const foundValue = labelcolor.filter(
obj => obj.status === task.status
)[0].class;
return (
<ListItem key={index} divider="true">
<div className={classes.taskwidth}>
<ListItemText
primary={
<React.Fragment>
{task.name} - {task.due_date}
</React.Fragment>
}
secondary={
<React.Fragment>
<Typography
component="span"
className={foundValue}
color="textPrimary"
>
{task.status}
</Typography>
</React.Fragment>
}
/>
</div>
</ListItem>
)}
)}

Resources