"react" Each child in a list should have a unique "key" prop - javascript

An error seems to occur because the key value is not entered in the map function, but I do not know how to modify the code.
The array is structured like this:
const tabContArr=[
{
tabTitle:(
<span className={activeIndex===0 ? "is-active" : ""} onClick={()=>tabClickHandler(0)}>0</span>
),
},
{
tabTitle:(
<span className={activeIndex===1 ? "is-active" : ""} onClick={()=>tabClickHandler(1)}>1</span>
),
},
{
tabTitle:(
<span className={activeIndex===2 ? "is-active" : ""} onClick={()=>tabClickHandler(2)}>2</span>
),
},
{
tabTitle:(
<span className={activeIndex===3 ? "is-active" : ""} onClick={()=>tabClickHandler(3)}>3</span>
),
}
];
An error occurs in the map function part.
{tabContArr.map((section)=>{
return section.tabTitle
})}

Try with React Fragments with a key attribute as mentioned in React docs
{tabContArr.map((section, index)=>{
return <React.Fragment key={`section-tab-${index}`}>{section.tabTitle}</React.Fragment>
})}

What you have done is not the right way.
If you have data, instead of passing the ReactElement into the array you should pass it into the map function like this:
{tabContArr.map((tab, index)=>{
return <span
className={activeIndex === index ? "is-active" : ""}
onClick={()=>tabClickHandler(index)}
key={`tab-${index}`}>index</span>
})}

Related

Javascript splice array method is not working as expected

,
I was working out with splice methods of js , but as it may seem it was not working exactly as it should remove any element from an array .
Currently its only deleting the last element from array even after providing the index value for it to delete from the array. in console.log i get the perfect output after deleting anything , but in UI part it does not update as it should , its only removing the last element from array even if i click on delete other item . How can i resolve this ?
Here's what i've tried so far :
const add_actions_options = [
{value : "Postback" , label:intl.formatMessage({ id: 'POSTBACK' })},
{value : "Uri" , label:intl.formatMessage({ id: 'URI' })}
]
const [ actions , setActions ] = useState<any | undefined>([{type : add_actions_options[0].value , label : "" , data : ""}])
const [selectOptions, setSelectOptions] = useState<any>(add_actions_options);
function addAction(){
if(actions.length < 4 ){
setSelectOptions([...add_actions_options])
setActions([...actions , {type : selectOptions[0].value , label : "" , data : ""}])
} else {
toast(intl.formatMessage({ id: 'MAX.ALLOWED.4' }), { type: "error" })
}
}
function deleteAction(index){
if(actions.length === 1 ){
toast(intl.formatMessage({ id: 'MIN.ALLOWED.1' }), { type: "error" })
} else {
const updatedFields = [...actions];
updatedFields.splice(index, 1);
console.log('index : ' , index)
console.log('updatedFields : ' , updatedFields)
setActions(updatedFields);
}
}
<div className='row my-6'>
<div className='col-lg-3 py-2'>
<h4><label className="form-label">{intl.formatMessage({ id: 'ACTIONS' })}*</label></h4>
<button className='btn btn-primary btn-sm btn-block' onClick={() => addAction()}>
<KTSVG path='/media/icons/duotune/arrows/arr075.svg' className='svg-icon-2' />
{intl.formatMessage({id: 'ADD.ACTION'})}
</button>
</div>
</div>
<div className='row my-6 '>
{ actions.map((item , index) => {
return(
<div key={index} className='row my-6'>
<div className='col-lg-4 py-2'>
<h4><label className="form-label">{intl.formatMessage({ id: 'TEMPLATE.TYPE' })}*</label></h4>
<Select
onChange={(value) => handleTypeChange(index, value)}
options={selectOptions}
/>
</div>
<div className='col-lg-3 py-2'>
<h4><label className="form-label">{intl.formatMessage({ id: 'TEMPLATE.LABEL' })}*</label></h4>
<input
{...formik_buttons_type.getFieldProps('action.label')}
className="form-control form-control-lg form-control-solid"
name='action.label'
id='action_label'
type="text"
maxLength={30}
onChange={(event) => handleLabelChange(index, event.target.value)}
value={actions.label}
required
onInvalid={(e) => checkLabelValidation(e)}
onInput={(e) => checkLabelValidation(e)}
/>
</div>
<div className='col-lg-3 py-2'>
<h4><label className="form-label">{intl.formatMessage({ id: 'TEMPLATE.DATA' })}*</label></h4>
<input
{...formik_buttons_type.getFieldProps('action.data')}
className="form-control form-control-lg form-control-solid"
name='action.data'
id='action_data'
type="text"
maxLength={100}
onChange={(event) => { handleDataChange(index, event.target.value); }}
value={actions.data}
required
onInvalid={(e) => checkDataValidation(e)}
onInput={(e) => checkDataValidation(e)}
/>
</div>
<div className='col-lg-2 py-2 mt-10'>
<OverlayTrigger
delay={{ hide: 50, show: 50 }}
overlay={(props) => (
<Tooltip {...props}>
{intl.formatMessage({ id: 'DEL.ACTION' })}
</Tooltip>
)}
placement="top">
<button
type='button'
style={{display: index === 0 ? 'none': 'inline-block'}}
className='btn btn-icon btn-md btn-bg-light btn-color-danger me-1'
onClick={() => deleteAction(index)}
>
<i className='fa fa-trash'></i>
</button>
</OverlayTrigger>
</div>
</div>
)
})}
</div>
I am able to receive exact index number perfect output from the logs below in deleteAction fields , but the view in browser deletes the last column(index) from the array of actions. :
console.log('index : ' , index)
console.log('updatedFields : ' , updatedFields)
can anyone help me with this ?
code sand box : https://codesandbox.io/s/vibrant-christian-bktnot
Thanks and Regards !
Whenever using the index as a key for an element. We have to ensure we are not modifying the state array to avoid bugs. If you are modifying as #Dave suggested use unique keys.
The problem here is using the index as key, When we remove an element from an array react compares the previous keys [0,1,2,3] with new keys [0,1,2].
If you notice closely, Even if we remove index (1) using splice(1,1) method. The elements which are rendered again have starting index of 0.
React compares keys previous keys [0,1,2,3] with new keys [0,1,2] and finds out that index 3 is removed hence it every time removes the 3rd element in the above example (or the last index) from DOM. However, your state is reflecting the correct array element.
To avoid this use a unique key.
Codesandbox for a working example.
If you are not having keys in objects, To generate unique keys we can use one of the following as per your use case:
crypto.randomUUID();
Date.now().toString(36) + Math.random().toString(36).substr(2)
https://reactjs.org/docs/lists-and-keys.html
We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state.
When you do
{ actions.map((item , index) => {
return(
<div key={index}
you are pretty much asking for issues with component state. When react is trying to determine which element in the UI to update, and it sees "the array with a length of 6 now has a length of 5, which element do I need to remove", it will find the one with a key that no longer exists, in this case the one at the end since you used index as key, and will remove it.
I would probably do
function randomId(){
const uint32 = window.crypto.getRandomValues(new Uint32Array(1))[0];
return uint32.toString(16);
}
const [ actions , setActions ] = useState<any | undefined>([{id: randomId(), type : add_actions_options[0].value , label : "" , data : ""}])
function addAction(){
if(actions.length < 4 ){
setSelectOptions([...add_actions_options])
setActions([...actions , {id: randomId(), type : selectOptions[0].value , label : "" , data : ""}])
} else {
toast(intl.formatMessage({ id: 'MAX.ALLOWED.4' }), { type: "error" })
}
}
{ actions.map((item) => {
return(
<div key={item.id}
where randomId can be anything that gives you a unique ID, or (even better) if there is an existing property on the actual data that uniquely identifies it, you could use that.

React native conditional rendering an array with 2 conditions

I have an array with several objects. Inside each object i have a field called type that can be either a or b. I am trying to conditional render a specific view for type a and a specific view for type b.
Here is my array:
DATA=[
{id:1, type:'a'},{id:2,type:'b'}
]
return(
{DATA.type === 'a' ?
<Text>I am type A</Text>
:
<Text>I am Type B </Text>
}
)
When i do that nothing appears on the screen.
UPDATE
DATA=[
{id:1, type:'a',locked:true},
{id:2,type:'b',locked:false}
]
const[isLocked,setIsLocked]=useState(false)
return(
{isLocked && DATA.map((item) => item.type === 'a')) ?
<Text>I am type A</Text>
:
null}
)
it is still not working. I am type A still appears on all pages of my carousel.
You need to map your array to accomplish it. Otherwise, you can't get the correct key.
DATA = [
{ id:1, type:a },
{ id:2, type:b },
]
return(
DATA.map((item) => item.type === 'a'
? <Text>I am type A</Text>
: <Text>I am Type B </Text>
))

Can I change the order of li elements conditionally in React

I have a list with side menu options, some of them are normal categories, some of them are static, here is my code:
//const type = the type is either categories or static
{items.map((item, index) => {
return (
<li>
{type !== 'categories' ? (
<> Static </>
) : (
<> Category </>
)}
</li>
);
})}
So in the items that are of type static I have a variable that comes from the back end which is called display, its value could be either 'top' or 'bottom', what I want to do is, if the type is equal to 'static', to move the order of the li to the value item.display has, for example:
<li>----</li> //type static //item.display: top
<li>++++</li> //type static //item.display: bottom
<li>""""</li> //type categories //item.display doesn't exist here
<li>::::</li> //type categories //item.display doesn't exist here
In the example above the li filled with the symbol '+' has a value of display: bottom,
so it should go to the bottom of the list and the list should now look like that:
<li>----</li> //type static //item.display: top
<li>""""</li> //type categories //item.display doesn't exist here
<li>::::</li> //type categories //item.display doesn't exist here
<li>++++</li> //type static //item.display: bottom
How can I implement that logic, I already tried doing it with inline styles like so:
<li style={{order: item.display === "top" ? items.length.toString() : "1"}}>
I am not even sure if this is a viable HTML, but it didn't work anyway, what are your suggestions for solving this problem?
You can control the order using items.sort() before you map it into virtual dom nodes.
Example:
import React from 'react'
function App() {
let items = [
{ text: '----', type: 'static', display: 'top' },
{ text: '++++', type: 'static', display: 'bottom' },
{ text: '""""', type: 'categories' },
{ text: '::::', type: 'categories' },
]
return (
<ul>
{items
.sort((a, b) =>
a.display === b.display
? 0
: a.display === 'top'
? -1
: a.display === 'bottom'
? 1
: 0,
)
.map(item => (
<li>
{item.type !== 'categories' ? (
<> Static </>
) : (
<> Category </>
)}
</li>
))}
</ul>
)
}
export default App
output:
<ul>
<li>----</li>
<li>""""</li>
<li>::::</li>
<li>++++</li>
</ul>
A possible solution would be that you have a mapping from string to number and a little helper function
const displayMap = {
top: 0,
default: 1,
bottom: 2
};
const compareDisplay(a,b){
let disp1 = a.display ?? 'default';
let disp2 = b.display ?? 'default';
return displayMap[disp1] > displayMap[disp2] ? 1 : -1;
}
in case if display is not defined, it will take default, which is mapped to the middle value
In case display also contains other values than top or bottom, you need to add a bit of logic to the helper function
you can use this mapping, to sort your objects before mapping
{
items.sort((a,b) => compareDisplay(a,b)).map((item, index) => {
return (
<li>
{
type !== 'categories' ?
(<> Static </>) :
(<> Category </>)
}
</li>
);
})}

Mapping a different icon depending on property value in React

https://codesandbox.io/s/r546o8v0kq
My above sandbox shows basic mapping of an array of items. This forms a list of notes, dates and an icon depending on what type of item it is.
I am working some logic that maps each item to find out what value it is, based on that I assign the value a string to complete the type of font awesome logo.
const noteType = _.uniq(notes.map(value => value.intelType));
const noteIcon = [
`${noteType}`.toUpperCase() == "EDUCATION"
? "paper-plane"
: `${noteType}`.toUpperCase() == "ELIGIBILITY"
? "heart"
: `${noteType}`.toUpperCase() == "GENERAL"
? "twitter"
: null
];
If "intelType" has a value of "education" it would return the "paper-plane" string to complete the icon. e.g fa fa-${noteIcon}
<List>
{notes.map((note, index) =>
note !== "" ? (
<React.Fragment>
<ListItem className="pl-0">
<i class={`fa fa-${noteIcon}`} aria-hidden="true" />
<ListItemText
secondary={moment(note.createdAt).format("DD-MMM-YYYY")}
/>
</ListItem>
<p>{note.note}</p>
<Divider />
</React.Fragment>
) : null
)}
</List>
Its not getting mapped and returning all three values, which does not meet any criteria therefore returns null as requested. I'm a bit stuck as what to do next here.
You can define an object that maps intel type to icon names:
const noteIconMap =
{ "EDUCATION": "paper-plane",
"ELIGIBILITY": "heart",
"GENERAL": "twitter",
};
And look it up this way inside the render:
<i class={`fa fa-${noteIconMap[note.intelType.toUpperCase()]}`} aria-hidden="true" />
Although, beware, if there is a case where note can have intelType undefined, toUpperCase call will throw an error.
Here's a link to working modified sandbox:
https://codesandbox.io/s/ojz2lzz03z
I'm not sure what's going on with this bit of code:
const noteIcon = [
`${noteType}`.toUpperCase() == "EDUCATION"
? "paper-plane"
: `${noteType}`.toUpperCase() == "ELIGIBILITY"
? "heart"
: `${noteType}`.toUpperCase() == "GENERAL"
? "twitter"
: null
]
But it makes more sense to me to store that information as an object and then access the icon type that way.
const icons = {
EDUCATION: 'paper-plane',
ELIGIBILITY: 'heart',
GENERAL: 'twitter'
}
And then going:
icons[noteType]
You need to get an icon in the map for each note.intelType. Since you're passing an array of ids, none of the icons is matched, and the result is always null.
A simple solution is to create a Map of types to icons (iconsMap), and get the icon from the Map using note.intelType.
btw - currently note.intelType us always uppercase, so you don't need to transform it.
sandbox
const iconsMap = new Map([
['EDUCATION', 'paper-plane'],
['ELIGIBILITY', 'heart'],
['GENERAL', 'twitter'],
]);
class Notes extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const { notes, classes } = this.props;
return (
<React.Fragment>
<List>
{notes.map((note, index) =>
note !== "" ? (
<React.Fragment>
<ListItem className="pl-0">
<i class={`fa fa-${iconsMap.get(note.intelType)}`} aria-hidden="true" />
<ListItemText
secondary={moment(note.createdAt).format("DD-MMM-YYYY")}
/>
</ListItem>
<p>{note.note}</p>
<Divider />
</React.Fragment>
) : null
)}
</List>
</React.Fragment>
);
}
}

Conditional link in JSX

I'm trying to write a way to render links conditionally. I have the following function:
const renderLinkIf = (content, condition, href) => {
if (condition) {
return (<Link to={href}>{content}</Link>);
}
return (content);
};
With very simple tasks it works:
{ renderLinkIf('test', true, '/dashboard') }
However, I can't figure out how to render more complex contents:
{renderLinkIf(
<span className={sectionCompleted(30) ? 'completed' : null}>
{sectionCompleted(30) ? <CheckIcon /> : <HeaderPersonalInfo />}
</span> Personal Info,
true,
'/dashboard',
)}
I just get Syntax Errors.
How can I pass more complex JSX through renderLinkIf to be rendered?
I believe you'd have to wrap the <span> and the text Personal Info in a single element for react. Other than that, I don't see any obvious errors:
{renderLinkIf(
<span><span className={sectionCompleted(30) ? 'completed' : null}>
{sectionCompleted(30) ? <CheckIcon /> : <HeaderPersonalInfo />}
</span> Personal Info</span>,
true,
'/dashboard',
)}

Categories

Resources