I need either annualPlans or monthlyPlans to map it depending if isAnually is true or not. and what is the safest way to put in the price?
I have a toggle button by the way which switches between the annualPlans and monthlyPlans.
How do it do it?
Here's my code below
{isAnnually
? annualPlans
: monthlyPlans.map((p, index) => (
<Fragment key={index}>
<PlanCard
id={p.value}
current={p.current}
title={p.name}
price={`$ ${
p.annual_price ? p.annual_price : p.monthly_price
}`}
/>
</Fragment>
));
}
You'll need to wrap your ternary condition in parenthesis before you call .map().
{(isAnnually ? annualPlans : monthlyPlans).map((p, index) => (
<Fragment key={index}>
<PlanCard
id={p.value}
current={p.current}
title={p.name}
/>
</Fragment>
))}
Related
my code got an map function that show item in a list :item that showing in the site
I need to write an if statement that olny show the item that same as the date above
code in react for the map function:
function Feed(props) {
console.table(props.data);
const number="";
return (
<>
{
props.data.map(item=> (
<>
<div className="taskcolorback-div" />
<button className="taskcolor-button" />
<input className="tasktext-b" defaultValue={item.fields.Title}></input>
<button className="taskwhite-button" />
<b className="timeinline">{item.fields.Hours}Hr</b>
<img className="vector-icon" alt="" src="icons8-chevron-right-64.png" />
</>
))
}
</>
)
}
// if your item has a date property and it's a string.
const component = /* the component you want to render */
item.fields.date === yourDate ? component : <p> write some error handling </p>
// at least you need some date data
You can use ternary operator instead of if statement.
return (
<>
{props.data.map(item =>
item.display === true ? (
<div>{/*Your component Here*/}</div>
) : null
)}
</>
)
I have a problem with key prop error in SummaryListItem Component.
Console shows me errors despite the fact, that underlined component DOES have an key prop with unigue ID.
{SIXTH_STEP_DATA.map(({ text, id }, index) => (
<CardWrapper elevation={1} key={id}>
<SummaryListItem
info={info}
key={id}
handleSetStep={handleSetStep}
viewContent={viewContent}
text={text}
index={index}
timeIntervalInMiliseconds={timeIntervalInMiliseconds}
/>
</CardWrapper>
))}
I tried to add also a dynamic id to another list wrapped inside this component (useId hook) but its also didnt helped.
<Card>
<Divider />
<StyledCardContent>
<StyledList disablePadding>
<StyledListItem disableGutters key={keyId}>
{viewContent ? (
<StyledLink variant='h4' onClick={() => handleSetStep(index + 1)}>
{t(text)}
</StyledLink>
) : (
<Typography variant='h4'>{t(text)}</Typography>
)}
</StyledListItem>
<ListItemAvatar>
{viewContent ? (
<LabelWrapper>{compileContent(summaryInfo)}</LabelWrapper>
) : (
<AvatarWrapperSuccess>
<Fade in={opacity} timeout={500}>
<CheckIcon />
</Fade>
</AvatarWrapperSuccess>
)}
</ListItemAvatar>
</StyledList>
</StyledCardContent>
</Card>
Wheres the issue ? I am pretty sure that component is given a proper key with id. This is the first time when this solution didnt worked.
EDIT : adding id from useId hook for SummaryListIteam instead of id used for CardWrapper also didnt helped :/ Strange.
Warning: Each child in a list should have a unique "key" prop
You need to use a unique property (like index, id, slug, unique random number).
{list.map((name, index) => (
<Name key={index}>
<h2 >
{name}
</h2>
</Name>
))}
I'm getting this error I read some ways to fix it , but nothing worked
<View style={styles.container}>
<StatusBar
backgroundColor="transparent"
translucent
barStyle={theme.dark ? 'light-content' : 'light-content'}
/>
{open ? (
<DateTimePicker
style={{width: '100%', margin: 5}}
mode="date"
value={date}
dateFormat="day month year"
display="calendar"
onChange={handleDate}
/>
) : (
<Button
style={{margin: 5}}
color="#17E5C2"
onPress={() => {
setOpen(true);
}}>
Filtrar por data
</Button>
)}
{Object.values(JSON.parse(route.params.paramKey).message).map(item =>
Object.values(item.createdAt[0]).filter(actualDate =>
actualDate.includes(dateFilter) ? (
<Card mode="outlined" key={uuidv4()}>
<Title>{item?.createdAt[0].value}</Title>
<Button
style={{alignItems: 'flex-start'}}
color="#17E5C2"
icon={
infoVisible
? 'arrow-up-bold-outline'
: 'arrow-down-bold-outline'
}
mode="outlined"
onPress={() => {
handleInfo();
}}>
Ver detalhes
</Button>
{Object.keys(item).map(data => (
<Card.Content
key={uuidv4()}
style={infoVisible ? {display: 'flex'} : {display: 'none'}}
accessible={false}>
<Paragraph style={{fontWeight: 'bold'}}>{data}</Paragraph> // {data} is a string as I checked in console.log
<Paragraph>{item[data][0]?.value}</Paragraph>
</Card.Content>
))}
<Card.Actions>
<Button color={'#17E5C2'}>Edit</Button>
</Card.Actions>
</Card>
) : (
console.log('NO ACTUAL DATA') // When I change console.log to a react child like(<Text>test</Text>) the error appear's instantly
),
),
)}
</View>
The error appear's when I choose a date that has data.
I tried to put console.log besids react child , and when I put it appears to me the data.
So I tought the error could be in my react childs.
I tried to fix my jsx conditional , but not worked , also tried to remove some commas , but also not worked,
and I tried to use <> </> at the top and the end , but also not worked
Complete error message: Error: Text strings must be rendered within a <Text> component.
I tried the entire day so.... it's been dificulty , I want some tips about how to fix it.
One possible problem I can see from your code
Object.values(item.createdAt[0]).filter(actualDate => actualDate.includes(dateFilter) ? <YourComponent> : console.log('NO ACTUAL DATA'))
You're using filter instead of map for a ternary condition.
filter returns true/false value, so you shouldn't use it in this case
If you want to use it, the proper one could be
Object.values(item.createdAt[0]).filter(actualDate => actualDate.includes(dateFilter))
This error comes when you are not wrapping strings within the component or if you are you using some code formatter it sometimes add {" "} outside the components. Check for these scenarios within your components (P.s:- commenting out code component by component might save you some time)
Warning: Each child in a list should have a unique "key" prop. Check the render method of ForwardRef(ListItem). It was passed a child from RecipientsList.
I have traced it down on the react-components debugger chrome tool. I have put the key props on the component but the warning still comes up.
Parent Component (Recipient List)
<List>
{recipientsResults.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((recipient, index) => (
<CustomList
key={Math.random() * 10}
title={recipient.account_holder_name}
subtitle={recipient.summary}
id={recipient.id}
avatar={"true"}
customClass={cx(styles.item)}
avatarClass={cx(styles.avatar)}
actions={[
<span className={cx(styles.action)}>
<Icon name="send" />
</span>,
<span className={cx(styles.action)}>
<Icon name={`${index === selectedIndex ? 'caret-up' : 'caret-down'}`} color="#C4C4C4" onClick={() => {
if (index === selectedIndex) {
setSelectedIndex(null)
} else (
handleBeneficiaryClick(index)
)
}} />
</span>
]}
collapsibleContent={
<CollapsibleContent
recipient={recipient}
isOpen={index === selectedIndex}
index={Math.random() * 10}
onDelete={(id) => handleDelete(id)}
onEdit={(id) => handleEdit(id)}
/>
}
/>
))}
</List>
}
Child Component (Custom List)
return (
<>
<ListItem
secondaryAction={
actions && actions
}
className={`${customClass}`}
key={Math.random() * 10}
>
{avatar &&
<ListItemAvatar>
<Avatar src={avatar} className={`${avatarClass}`}>
{getInitials(title)}
</Avatar>
</ListItemAvatar>
}
<ListItemText
primary={title}
secondary={subtitle ? subtitle : null}
/>
</ListItem>
{collapsibleContent && collapsibleContent}
</>
)
remove this line
replace this with something like index or recipient.id. react needs a way to "associate" a key with an item from your array. this means by using a random you are telling react that the jsx is a different item derived from an item(given item = someArray[index]) for every render.
Can I ask why you're using math random for generating keys? Also see: Is it okay to use Math.random() for keys?. It is very likely the issue.. You can instead use your index argument, that you have on your map.
I finally got the answer, under Custom list component, i needed to change:
this:
<>
</>
to:
<React.Fragment key={index}>
</React.Fragment>
Got it from:
https://stackoverflow.com/a/68014086/4831770
using a ternary statement to render different JSX depending on shouldRenderPlanA property (which resolves true or false). Issue however is that an error appears at the shouldRenderPlanA ternary check with the following:
"Unexpected token ?, expected the token :"
Can anyone explain where I might be going wrong? TIA
return (
<>
{options.map(option)}
<StyledRow>
{variousOptions.map((opt) => (
{shouldRenderPlanA ? (
<StyledLabelOptionOne
variousProps={variousProps}
/>
) : (
<StyledLabelOptionTwo
variousProps={variousProps}
/>
)}
))}
</StyledRow>
</>
);
My suspicion is that it's something to do with the check happening inside the map?
You cannot use nested braces {} in JSX, remove the inner ones and it will work:
return (
<>
{options.map(option)}
<StyledRow>
{variousOptions.map((opt) => shouldRenderPlanA ? (
<StyledLabelOptionOne
variousProps={variousProps}
/>
) : (
<StyledLabelOptionTwo
variousProps={variousProps}
/>
))}
</StyledRow>
</>
);
Here's the problem.
(
{shouldRenderPlanA ? (
You can't expect to return an object, instead
(shouldRenderPlanA ?
Or try to write something simple at the beginning , ex. flag?1:0 to get it working before plugging other things :)
You have an error because you didn't return a value inside the map
Maybe this can help you
return (
<>
{options.map(option)}
<StyledRow>
{variousOptions.map((opt) => {
return shouldRenderPlanA ? (
<StyledLabelOptionOne
variousProps={variousProps}
/>
) : (
<StyledLabelOptionTwo
variousProps={variousProps}
/>
}
))}
</StyledRow>
</>
);
You muset remove the parentheses, and return the element